Home > Web Front-end > JS Tutorial > The understanding of this in js

The understanding of this in js

一个新手
Release: 2017-10-11 09:48:04
Original
1766 people have browsed it

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
Copy after login

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
Copy after login

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
Copy after login

Case 5: If the execution environment of the function is changed through call or apply, this will 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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template