Basic query on passing this to a function

后端 未结 4 667
长发绾君心
长发绾君心 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:29

    this context in JavaScript depends on how the function is being called. See What does "this" mean?.

    1. this will refer to window

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

      Here, foo is globally defined function and the call to foo() is like window.foo(), Thus this inside foo() refers to the window object.

    2. Uncaught SyntaxError: Unexpected token this(…) on chrome console.

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

      this is reserved keyword and cannot be used as identifier name. Also note that no parameter is passed to foo() when invoking the function.

    3. undefined is logged in below code

      var that = this; // Global that
      
      function foo(that) { // Parameter `that`
          console.log(that); // <-- Use semicolon here
      }
      foo(); // `that` is not passed.
      

      because that passed as parameter overshadows the global that. And as nothing is passed to foo(), undefined is logged.

提交回复
热议问题