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
obj.getFoo()
returns an equation assigned to f .f is called via
f()
without an explicit caller, so this is justwindow
.If you want to get "obj", you can do this
Because, where
f()
actually runs,this
iswindow
. Since the context is not changed throughcall
orbind
, the output iswindow
.You can replace it as follows:
The
self
here points towindow
, soreturn self.foo
isreturn 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() 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
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