Basic query on passing this to a function

后端 未结 4 736
长发绾君心
长发绾君心 2021-01-26 00:50

I am trying to understand JavaScript this better.

function foo() {
    console.log(this);
}
// normal function call
foo(); // `this` will refer to `window`
         


        
4条回答
  •  既然无缘
    2021-01-26 01:28

    this refers to the current context of execution in Javascript. This context is something that Javascript keeps to itself and it is readonly. You can only read the variables available in that context. You cannot override it. When you do something like this:

    function foo(this){
        console.log(this);
    }
    foo();
    

    with the parameter this in the function, you are trying to overwrite the current context which is not allowed and hence you get the error.

    And, when you run this code:

    var that = this;
    function foo(that){
        console.log(that):
    }
    foo();
    

    you are not passing any parameter while calling the foo function and hence the value of that is undefined. Note that the earlier assignment of this to that is overwritten in this foo function context.

    Refer this link and this to know more about execution context.

提交回复
热议问题