In addition to closures, the incomprehensible concept of JS should also be the first: this, which is often confusing, today, let's take a good look at its true nature. In addition to closures, this concept should also be the first to bear the brunt: this, which is often confusing, now let's take a good look at its true nature.
Define an object:
Var Charles = {living: true, age: 23, gender: male, getGender: function () {return Charles. gender ;}}; console. log (Charles. getGender (); // output: male
The following code has the same effect:
Var Charles = {living: true, age: 23, gender: male, getGender: function () {return this. gender; // note "this" }}; console. log (Charles. getGender (); // output: male
So what exactly does this refer to in the code? How can we analyze it, because it is sometimes difficult to distinguish the true colors of this in a specific environment. Now, remember one sentence:
When the host function of this value is encapsulated in another function or called in the context of another function, this value is always a reference to the global (head/window) object.
That is to say, this value is always pointed to window in the nested function for es5.
Var myObject = {myProperty: 'I can see the light', myMethod: function () {var that = this; console. log (this); // output: 'object (here myObject) 'var helperFunction = function () {console. log (that. myProperty); // output 'I can see the light' console. log (this); // If 'that 'is not used, the 'window' is output, because it is} () in the nested function; // execute now} myObject. myMethod (); // call myMethod
In combination with the above sentence, for ES5, this is also the case:
Var myObject = {func1: function () {console. log (this); // output 'object' (first-level function) var func2 = function () {console. log (this); // from this point on, this is window (second-level function) var func3 = function () {console. log (this); // Of course window} () ;}() ;}} myObject. func1 ();
Here, we should understand the position of this in JS. I believe it will not be clear in the future.