Home > Article > Web Front-end > Detailed explanation of application and call usage examples of javascript changing the internal point of the function body
call and apply both exist to change the context that is, the context when a certain function is running. In other words, to Change the pointer of this inside the function body.
call and apply have exactly the same function, but the way they accept parameters is different.
Method definition
apply
Function.apply(obj,args) method can receive two parameters:
obj: This object will replace this object in the Function class
args: This is an array or array-like, and the apply method takes the elements in this collection Passed as a parameter to the called function.
call
The first parameter of the call method is the same as the first parameter of the apply method , except The second parameter is a parameter list
In non-strict mode, when the first parameter is passed as null or undefined, this in the function body will point to the default host object. In the browser It is window
var test = function(){ console.log(this===window); } test.apply(null);//true test.call(undefined);//true
Usage
"Hijacking" method of others
At this time, the logName method in foo will be referenced by bar, this points to bar
var foo = { name:"mingming", logName:function(){ console.log(this.name); } } var bar={ name:"xiaowang" }; foo.logName.call(bar);//xiaowang
Implementing inheritance
##
function Animal(name){ this.name = name; this.showName = function(){ console.log(this.name); } } function Cat(name){ Animal.call(this, name); } var cat = new Cat("Black Cat"); cat.showName(); //Black CatIn actual development, we often encounter this pointer A scene that was inadvertently changed.
There is a local
fun method. When fun is called as a normal function, fun internal this points to window, but we often want it to point to the #test node, see the following code:
window.id="window"; document.querySelector('#test').onclick = function(){ console.log(this.id);//test var fun = function(){ console.log(this.id); } fun();//window }Use
call ,applyWe can easily solve this problem
window.id="window"; document.querySelector('#test').onclick = function(){ console.log(this.id);//test var fun = function(){ console.log(this.id); } fun.call(this);//test }Of course you can also do this, but in
ECMAScript 5# In ##strict mode, this in this case has been stipulated not to point to the global object, but to undefined:
##window.id="window"; document.querySelector('#test').onclick = function(){ var that = this; console.log(this.id);//test var fun = function(){ console.log(that.id); } fun();//test }
function func(){ "use strict" alert ( this ); // 输出:undefined } func();
The above is the detailed content of Detailed explanation of application and call usage examples of javascript changing the internal point of the function body. For more information, please follow other related articles on the PHP Chinese website!