Home > Web Front-end > JS Tutorial > body text

Deeply understand the this keyword in JS

迷茫
Release: 2017-03-26 17:44:23
Original
1471 people have browsed it

After completing my graduate defense, I began to continue working hard for a career change. Xiaobai is going to struggle, come on. This article is quoted from the JS core series: A brief discussion of the scope of functions.

In a function, this always points to the owner object of the current function. The specific point of this can only be determined at runtime, and its calling object can only be known.

window.name = "window";
function f(){
    console.log(this.name);
}
f();//输出window

var obj = {name:'obj'};
f.call(obj); //输出obj
Copy after login

When f() is executed, the caller of f() is the window object, so "window" is output.

f.call(obj) puts f() on the obj object and executes it, which is equivalent to obj.f(). At this time, this in f is obj, so the output is "obj".

code1:

var foo = "window";
var obj = {
    foo : "obj",
    getFoo : function(){
        return function(){
            return this.foo;
        };
    }
};
var f = obj.getFoo();
console.log(1+":"+f()); //输出window
Copy after login

code2:

var foo = "window";
var obj = {
    foo : "obj",
    getFoo : function(){
        var that = this;
        return function(){
            return that.foo;
        };
    }
};
var f = obj.getFoo();
console.log(f()); //输出obj
Copy after login

code1:
Executing var f = obj.getFoo() returns an anonymous function, equivalent to:
var f = function(){
Return this.foo;
}
f() is equivalent to window.f(), so this in f points to the window object, and this.foo is equivalent to window.foo, so f() returns "window"

code2:
Executing var f = obj.getFoo() also returns an anonymous function, that is:
var f = function(){
return that.foo;
}
The only difference is that this in f becomes that. Before knowing which object that is, first determine the scope chain of f: f->getFoo-> ;window and search for that on the chain, you can find that that refers to this in getFoo, and this in getFoo points to the caller of its runtime. From var f = obj.getFoo(), we know that this points to is an obj object, so that.foo is equivalent to obj.foo, so f() returns "obj".

Students who are unclear about the scope chain can refer to JavaScript from Scope to Closure.

The above is the detailed content of Deeply understand the this keyword 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