亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

javascript - Pointing issues about this
天蓬老師
天蓬老師 2017-06-28 09:25:33
0
5
865
var foo = "window";
var obj = {
    foo : "obj",
    getFoo : function(){
        return function(){
            return this.foo;
        };
    }
};
var f = obj.getFoo();
console.log(f());  //結(jié)果:window

Why is the result of the above code running window?

天蓬老師
天蓬老師

歡迎選擇我的課程,讓我們一起見證您的進步~~

reply all(5)
滿天的星座

obj.getFoo() returns an equation assigned to f .
f is called via f() without an explicit caller, so this is just window .

If you want to get "obj", you can do this

var foo = "window";
var obj = {
    foo : "obj",
    getFoo : function(){
        var self = this;
        return function(){
            return self.foo;
        };
    }
};

var f = obj.getFoo();
console.log(f());
阿神

Because, where f() actually runs, this is window. Since the context is not changed through call or bind, the output is window.

You can replace it as follows:

console.log(f());
// ----->
console.log(obj.getFoo());
// ----->
console.log(function() {
    var self = this;
    return function() {
        return self.foo
    }
});

The self here points to window, so return self.foo is return window.foo, which is 'window'.

淡淡煙草味

In fact, the simplest understanding is that obj.getFoo gives f, and then look at where this method runs.

f = function () {
    return function () {
        return this.foo
    }
}
曾經(jīng)蠟筆沒有小新

f() in console.log(f()) is called independently
1. If the caller function is owned by an object, then when the function is called, the internal this points to the object.
2. If the function is called independently, then this inside the function points to undefined.
Recommended reading http://www.jianshu.com/p/d647... I hope it will be helpful to you

Ty80

Function execution, this in the function body points to the caller of the function

1. In the following code, the caller of the getFoo function is obj, so this inside the getFoo function points to the obj object

var f = obj.getFoo()

2. The getFoo function returns an anonymous function and assigns it to the variable f, and then executes the function f. At this time, the variable f is mounted on the window. The caller of the function f is the window, and this inside the function f also points to the window

console.log(f());  //結(jié)果:window
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template