Home >Web Front-end >JS Tutorial >Learn detailed explanation and working principle of this example in javaScript_Basic knowledge
How this works
If a function is called as a method of an object, then this will be assigned to the object.
Note that this behavior is very "fragile". If you get a reference to a method and call it, the value of this will not be the parent, but the window global object. This confuses most developers.
.call, .apply and .bind methods are used to operate the method of calling functions and help us define the value of this and the parameter values passed to the function.
Function.prototype.call can have any number of parameters, the first parameter is assigned to this, and the rest are passed to the calling function.
Function.prototype.bind creates a special function that will always use the parameters passed to .bind as the value of this, and can assign some parameters to create a curried version of the original function.
In the following example, this will not remain unchanged in the scope chain. This is a flaw in the rules, and often causes confusion for amateur developers.
A common method is to create a local variable to hold a reference to this, and there cannot be a variable with the same name in the child scope. A variable with the same name in the child scope will overwrite the reference to this in the parent scope. http://www.cnblogs.com/sosoft/
Unless you really want to use both this of the parent scope and the current this value, for some inexplicable reason, I prefer to use the .bind function. This can be used to assign this from the parent scope to the child scope.