This is a platitude topic in JavaScript, today I read some blogs, and then combined with their own understanding, write a blog record

var obj = {
  foo: function () { 
      console.log(this.bar)
  },
  bar: 1
};
var foo = obj.foo;
var bar = 2;
obj.foo() // 1
foo() // 2
Copy the code

Obj.foo () and foo() are the same function. Why is the output different? Because functions run in different environments. The function obj.foo() runs inside obj, and the function foo() runs globally. Inside obj, the value of bar is 1, and the value of global bar is 2

Memory data structure

  • JavaScriptThe reason language hasthisDesign, with the data structure in memory.
  • JavaScriptThe engine will generate an object in memory, and then copy the memory address of that object to the variable.

Example:

    var obj = {
        foo : 5 
    }
Copy the code

The obj variable actually refers to the address of the {foo: 5} object. If we want to read obj.foo, the engine reads the memory address from obj and then reads the original object from that address, returning its foo attribute. The original object is stored as a dictionary deconstruction, with each attribute name corresponding to an attribute description object. {foo: 5} storage is

    foo : {
        value:5,
        xxxx1:true,
        xxxx2:true
    }
Copy the code

But foo is probably a function. If it is a function, the engine will fade it out to memory and then assign the address of the function to foo’s property value

Var foo = {foo:function () {}} // foo is a function so that foo's value is not a value but a memory address foo: {value:0X1100001110111 // Memory address xxxx1:true, xxxx2:true}Copy the code

Since a function is a single value, it can be executed in different environments and now the problem is that functions can be executed in different environments, so there needs to be a mechanism to get the current context inside the function body. So, here comes this, which is designed to be inside the function body and refers to the environment in which the function is currently running.