I have seen a lot of information saying that which object calls this function, this in this function points to this object.
In the following example, the function foo is called through the statement foo(). Why does this point to the global world? Isn't Window.foo() called by the global object?
Please advise, thank you!
var x = 10;
var obj = {
x: 20,
f: function () {
var foo = function (){
console.log(this.x);
}
foo();
}
};
obj.f(); //10
There is a problem with what was said upstairs. Foo is not a global variable. A simple way to judge (non-strict mode) is:
1. When a function is not assigned a superior object, this points to window
2. When a function is assigned When it comes to superior objects, this only points to the closest superior (parent) object
such as foo.fn.o(), this in o points to fn
This is what it looks like, I wrote it in the comments
For
internal functions
, that is, functions declared in the body of another function, they will be bound to theglobal object
. This is adesign flaw of JavaScript
. The correct design method is that this of the internal function should be bound to the object corresponding to its outer function, thus causing the above problems.In order to avoid this design flaw, you can use
variable substitution
. As a rule, you can useself
orthat
. The code is as follows:First of all, let’s understand one thing:
1: window is also an object, it is a special object, it represents the whole world. When you call a function in the following way:
function foo(){....}
foo();//
This calling method in the second line (there is no object defined by you in front of the function), We call it 'global call'. In fact, it is equivalent to window.foo(). So did you see it? Calling a function globally is actually a special case of calling a function on an object, because the object at this time is window.
2: So why does the above code call foo() globally instead of on obj? I'll change the code and let it output 20:
Compare the two pieces of code and find their differences.
You can rewrite the code like this:
Through the above example, you can understand that when calling a function, the JavaScript parser is called in the form of call or apply. In this way, specify a value for this in the function. The first parameter of these two methods is the internal this value of the foo method when it is called. If the first parameter of the call method is null or undefined, the global object will be used as the first parameter by default (you can try Try foo.call(), foo.call(null), foo.call(undefined))
Function within function, this pointer is lost