Preface:This object will only work when strict mode is not used. The this object is bound by the execution environment of the function at runtime.
Case 1: In the global function, this is equal to window. Only when the function is called as a method of an object, this will be equal to that object. If you still don’t know what a global function is, please refer here and click to open the link
Case 2: The execution environment of the anonymous function is global, this usually points to the window
For example
var name = "window"; var object = { name: "Object name", getNameFunc: function () { return function (){ return this.name; }; } }; console.log(object.getNameFunc() ()); // 输出window
Case 3: Save the this object in the external scope in a variable that can be accessed by the closure, so that this can point to the this object in the scope
For example
var name = "window"; var object = { name: "Object name", getNameFunc: function () { var that = this; return function (){ return that.name; }; } }; console.log(object.getNameFunc() ()); // 输出Object name
Case 4: Assign the function first and then execute it, the value of this cannot be maintained
For example
var name = "window"; var object = { name: "Object name", getName: function () { return this.name; } }; console.log((object.getName = object.getName) ()); // 输出window
Case 5: If the execution environment of the function is changed through call or apply, thiswill point to other objects
The above is the detailed content of The understanding of this in js. For more information, please follow other related articles on the PHP Chinese website!