Home >Web Front-end >JS Tutorial >Understanding this object in JavaScript (code example)

Understanding this object in JavaScript (code example)

不言
不言forward
2018-10-29 14:29:122388browse

The content this article brings to you is about the understanding of this object in JavaScript (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Foreword: I have recently been reading Javascript Advanced Programming. For me, the Chinese version of the book has a lot of unsatisfactory translations, so I try to interpret it using what I understand. If there are any mistakes or omissions, we will be very grateful for your pointing them out. Most of the content in this article is quoted from "JavaScript Advanced Programming, Third Edition".

This object is based on the execution environment binding of the function at runtime:

In the global environment, this is equal to window, and when the function is called as a method of an object, this is pointed to that object.

However, the execution environment of anonymous functions is global, so its this object usually points to window.

Using this object in a closure may cause some problems.

Sometimes this may not be so obvious due to the way closures are written.

// 在全局环境中,this等于window
function thisBoundForWindow(){
    console.log(this);
    console.log(this.name);
}
thisBoundForWindow(); // Window
var o = new Object();
o.name = "Shaw";
//当函数被作为某个对象的方法调用时,this就指向了那个对象。
thisBoundForWindow.apply(o); // {name: "Shaw"}; "Shaw" ;
//在闭包中使用this对象可能会导致一些问题。
//有时候由于编写闭包的方式不同,这一点可能不会那么明显。
var name = "The Window";
var object = {
    name: "My Object",
    getNameFunc: function() {
        return function() {
            console.log(this.name);
        }
    }
}
object.getNameFunc()(); // "The Window"
/*
object.getNameFunc return=> function() {
        return function() {
            console.log(this.name);
        }
    }  => ()调用,还是在全局环境下调用的,所以this.name = window.name => "The Window"
*/

The above code first creates a global variable name, and then creates an object containing the name attribute.

This object also contains a method-getNameFunc(), which returns an anonymous function, and the anonymous function returns this.name. This anonymous function is a closure.

Let’s review the definition of “closure”:

A function that has access to variables in another scope is a closure.

Since getNameFunc() returns a function, calling object.getNameFunc()() will call the function it returns. The result is that a character is printed out on the console.

However, the character returned in this example is "The Window", which is the value of the global name variable.

So, how to point this to the object in the example?

Save the this object in the external scope in a variable that the closure can access, so that the closure can access the object. (Note that this method is also often used when using callback functions).

var name = "The Window";
var object = {
    name: "My Object",
    getNameFunc: function(){
        var that = this;
        return function() {
            console.log(that.name);
        }
    }
}
object.getNameFunc()(); // "My Object"
/*
// 伪代码过程
object.getNameFunc  execute
=> this = object = that 
=>function() {console.log(that.name);}  
=> ()
=> that.name = object.name 
=> "My Object" 
*/

Before defining the anonymous function, assign the this object to a variable named that.

After defining the closure, the closure can also access this variable, because it is a variable we specifically declared in the containing function.

Even after the function returns, that still refers to the object, so calling Object.getNameFunc() returns "My Object".

Under several special circumstances, the value of this may change unexpectedly. For example, the following code modifies the results of the previous example.

var name = "The Window";
var object = {
    name: "My Object",
    getName: function() {
        console.log(this.name);
    }
};
object.getName(); // "My Object"
(object.getName)(); // "My Object"
(object.getName = object.getName)(); // "The Window"

The first line of code calls object.getName() as usual, and returns "My Object" because this.name is object.name.

The second line of code adds parentheses before calling this method. Although after adding the parentheses, it seems to be referencing a function, the value of this is maintained because object.getName and (object .getName) definition is the same.

The third line of code first executes an assignment statement, and then calls the result of the assignment. Because the assignment expression is the function itself, the value of this is not maintained, and "The Window" is returned.

//第三个例子伪代码
//理解此段代码,首先要明确一个知识点:赋值语句是有返回值的,返回值就是所赋的值(也就是‘=’右边的值)。

(object.getName = object.getName)(); // "The Window"

(object.getName = function(){ console.log(this.name)})();

(function(){console.log(this.name)})();
//所以this指向window

Of course, we are unlikely to call this method like the second and third lines of code. It’s okay if you don’t understand it for the time being. This example helps illustrate that even subtle changes in syntax may accidentally change the value of this.

The above is the detailed content of Understanding this object in JavaScript (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete