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?
歡迎選擇我的課程,讓我們一起見證您的進步~~
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
}
}
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
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