React function and “this”









up vote
0
down vote

favorite












I know about "this" binding and all other stuff here, except one thing. I can't understand how "this" is not undefined in the first call, but second?



P.S. I know about function reference and that in the first case it's executing function but in the second case returning reference.



import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component
constructor()
super();
this.name = "MyComponent";
// this.handleClick = this.handleClick.bind(this);


handleClick()
console.log(this);
console.log(this.name);


render()
return (
<div>
<button onClick=this.handleClick()>click 1</button>
<button onClick=this.handleClick>click 2</button>
</div>
);



const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);









share|improve this question



















  • 4




    By writing onClick=this.handleClick() you are invoking the this.handleClick function directly on render, and it evaluates to onClick=undefined. That's why clicking on the click 1 button doesn't do anything. This is a great read on why this behaves like it does in the click 2 button case.
    – Tholle
    Nov 12 at 0:00










  • Please include the relevant code in the question text itself. Questions should make sense even if the link breaks in the future.
    – Håken Lid
    Nov 12 at 0:00














up vote
0
down vote

favorite












I know about "this" binding and all other stuff here, except one thing. I can't understand how "this" is not undefined in the first call, but second?



P.S. I know about function reference and that in the first case it's executing function but in the second case returning reference.



import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component
constructor()
super();
this.name = "MyComponent";
// this.handleClick = this.handleClick.bind(this);


handleClick()
console.log(this);
console.log(this.name);


render()
return (
<div>
<button onClick=this.handleClick()>click 1</button>
<button onClick=this.handleClick>click 2</button>
</div>
);



const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);









share|improve this question



















  • 4




    By writing onClick=this.handleClick() you are invoking the this.handleClick function directly on render, and it evaluates to onClick=undefined. That's why clicking on the click 1 button doesn't do anything. This is a great read on why this behaves like it does in the click 2 button case.
    – Tholle
    Nov 12 at 0:00










  • Please include the relevant code in the question text itself. Questions should make sense even if the link breaks in the future.
    – Håken Lid
    Nov 12 at 0:00












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I know about "this" binding and all other stuff here, except one thing. I can't understand how "this" is not undefined in the first call, but second?



P.S. I know about function reference and that in the first case it's executing function but in the second case returning reference.



import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component
constructor()
super();
this.name = "MyComponent";
// this.handleClick = this.handleClick.bind(this);


handleClick()
console.log(this);
console.log(this.name);


render()
return (
<div>
<button onClick=this.handleClick()>click 1</button>
<button onClick=this.handleClick>click 2</button>
</div>
);



const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);









share|improve this question















I know about "this" binding and all other stuff here, except one thing. I can't understand how "this" is not undefined in the first call, but second?



P.S. I know about function reference and that in the first case it's executing function but in the second case returning reference.



import React from "react";
import ReactDOM from "react-dom";

import "./styles.css";

class App extends React.Component
constructor()
super();
this.name = "MyComponent";
// this.handleClick = this.handleClick.bind(this);


handleClick()
console.log(this);
console.log(this.name);


render()
return (
<div>
<button onClick=this.handleClick()>click 1</button>
<button onClick=this.handleClick>click 2</button>
</div>
);



const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);






javascript reactjs this






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 12 at 5:01









Dinesh Pandiyan

2,173824




2,173824










asked Nov 11 at 23:54









Hayk

20435




20435







  • 4




    By writing onClick=this.handleClick() you are invoking the this.handleClick function directly on render, and it evaluates to onClick=undefined. That's why clicking on the click 1 button doesn't do anything. This is a great read on why this behaves like it does in the click 2 button case.
    – Tholle
    Nov 12 at 0:00










  • Please include the relevant code in the question text itself. Questions should make sense even if the link breaks in the future.
    – Håken Lid
    Nov 12 at 0:00












  • 4




    By writing onClick=this.handleClick() you are invoking the this.handleClick function directly on render, and it evaluates to onClick=undefined. That's why clicking on the click 1 button doesn't do anything. This is a great read on why this behaves like it does in the click 2 button case.
    – Tholle
    Nov 12 at 0:00










  • Please include the relevant code in the question text itself. Questions should make sense even if the link breaks in the future.
    – Håken Lid
    Nov 12 at 0:00







4




4




By writing onClick=this.handleClick() you are invoking the this.handleClick function directly on render, and it evaluates to onClick=undefined. That's why clicking on the click 1 button doesn't do anything. This is a great read on why this behaves like it does in the click 2 button case.
– Tholle
Nov 12 at 0:00




By writing onClick=this.handleClick() you are invoking the this.handleClick function directly on render, and it evaluates to onClick=undefined. That's why clicking on the click 1 button doesn't do anything. This is a great read on why this behaves like it does in the click 2 button case.
– Tholle
Nov 12 at 0:00












Please include the relevant code in the question text itself. Questions should make sense even if the link breaks in the future.
– Håken Lid
Nov 12 at 0:00




Please include the relevant code in the question text itself. Questions should make sense even if the link breaks in the future.
– Håken Lid
Nov 12 at 0:00












1 Answer
1






active

oldest

votes

















up vote
4
down vote



accepted










In the first line



<button onClick=this.handleClick()>click 1</button>


this.handleClick() will be executed in the render function of App component (which is a class by itself) while the component is being rendered in virtual DOM. So by the time of execution, handleClick function will be defined in the execution context which is App class.



In the second line



<button onClick=this.handleClick>click 1</button>


this.handleClick is attached to the DOM and will execute from the DOM's context when click event happens and the execution will look for handleClick in the DOM's context and will be undefined.



There are two ways to circumvent this



  1. bind the method to the class as you did.


  2. Pass in an anonymous function which will execute without DOM's context and by default be bound to invoker's context.


like this



<button onClick=(e) => this.handleClick(e)>click 1</button>





share|improve this answer




















    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254436%2freact-function-and-this%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes








    up vote
    4
    down vote



    accepted










    In the first line



    <button onClick=this.handleClick()>click 1</button>


    this.handleClick() will be executed in the render function of App component (which is a class by itself) while the component is being rendered in virtual DOM. So by the time of execution, handleClick function will be defined in the execution context which is App class.



    In the second line



    <button onClick=this.handleClick>click 1</button>


    this.handleClick is attached to the DOM and will execute from the DOM's context when click event happens and the execution will look for handleClick in the DOM's context and will be undefined.



    There are two ways to circumvent this



    1. bind the method to the class as you did.


    2. Pass in an anonymous function which will execute without DOM's context and by default be bound to invoker's context.


    like this



    <button onClick=(e) => this.handleClick(e)>click 1</button>





    share|improve this answer
























      up vote
      4
      down vote



      accepted










      In the first line



      <button onClick=this.handleClick()>click 1</button>


      this.handleClick() will be executed in the render function of App component (which is a class by itself) while the component is being rendered in virtual DOM. So by the time of execution, handleClick function will be defined in the execution context which is App class.



      In the second line



      <button onClick=this.handleClick>click 1</button>


      this.handleClick is attached to the DOM and will execute from the DOM's context when click event happens and the execution will look for handleClick in the DOM's context and will be undefined.



      There are two ways to circumvent this



      1. bind the method to the class as you did.


      2. Pass in an anonymous function which will execute without DOM's context and by default be bound to invoker's context.


      like this



      <button onClick=(e) => this.handleClick(e)>click 1</button>





      share|improve this answer






















        up vote
        4
        down vote



        accepted







        up vote
        4
        down vote



        accepted






        In the first line



        <button onClick=this.handleClick()>click 1</button>


        this.handleClick() will be executed in the render function of App component (which is a class by itself) while the component is being rendered in virtual DOM. So by the time of execution, handleClick function will be defined in the execution context which is App class.



        In the second line



        <button onClick=this.handleClick>click 1</button>


        this.handleClick is attached to the DOM and will execute from the DOM's context when click event happens and the execution will look for handleClick in the DOM's context and will be undefined.



        There are two ways to circumvent this



        1. bind the method to the class as you did.


        2. Pass in an anonymous function which will execute without DOM's context and by default be bound to invoker's context.


        like this



        <button onClick=(e) => this.handleClick(e)>click 1</button>





        share|improve this answer












        In the first line



        <button onClick=this.handleClick()>click 1</button>


        this.handleClick() will be executed in the render function of App component (which is a class by itself) while the component is being rendered in virtual DOM. So by the time of execution, handleClick function will be defined in the execution context which is App class.



        In the second line



        <button onClick=this.handleClick>click 1</button>


        this.handleClick is attached to the DOM and will execute from the DOM's context when click event happens and the execution will look for handleClick in the DOM's context and will be undefined.



        There are two ways to circumvent this



        1. bind the method to the class as you did.


        2. Pass in an anonymous function which will execute without DOM's context and by default be bound to invoker's context.


        like this



        <button onClick=(e) => this.handleClick(e)>click 1</button>






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Nov 12 at 3:01









        Dinesh Pandiyan

        2,173824




        2,173824



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.





            Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


            Please pay close attention to the following guidance:


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53254436%2freact-function-and-this%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            這個網誌中的熱門文章

            Barbados

            How to read a connectionString WITH PROVIDER in .NET Core?

            Node.js Script on GitHub Pages or Amazon S3