search

Home  >  Q&A  >  body text

Usage of this - Questions about this in Javascript. When a function is called as a method of an object, this refers to the superior object.

I saw the second usage environment when the master introduced this. The original text is here:
http://www.ruanyifeng.com/blo...
The object o here should be this? If so why is this least congruent?

function test(){
    console.log(this.x);
  }
  var o = {};
  o.x = 1;
  o.m = test;
   console.log(o.m());
   console.log(o===this);

The output is:
1
false

淡淡烟草味淡淡烟草味2709 days ago681

reply all(4)I'll reply

  • 过去多啦不再A梦

    过去多啦不再A梦2017-06-14 10:56:15

    This===window in global view

    reply
    0
  • 漂亮男人

    漂亮男人2017-06-14 10:56:15

    When console.log() is executed in the global environment, this of course points to the window;
    this points to the current execution environment of the function

    reply
    0
  • PHP中文网

    PHP中文网2017-06-14 10:56:15

    o.m() implicitly binds this to the o object
    In the global scope, this points to the global object

    reply
    0
  • 仅有的幸福

    仅有的幸福2017-06-14 10:56:15

    Remember, there is another calling method func.call(context, x, m). The above two methods are just syntax sugar. You can use "conversion code" method such as:

    function test(){
        console.log(this.x);
      } 

    is equivalent to

    function test(){
        console.log(this.x);
      }
    test.call(undefined)

    Logically speaking, the printed this should be undefined
    But there is a rule in the browser:

    If the context you pass is null or undefined, then the window object is the default context (the default context in strict mode is undefined)
    So the this above should correspond to window.

    reply
    0
  • Cancelreply