Home > Article > Web Front-end > javaScript uses call and apply
This time I will bring you javaScriptUsing call and apply, what are the precautions for using call and apply in javaScript, the following is a practical case, let's take a look.
call method:
Syntax: call(thisObj,Object)
Definition: Call a method of a object, Replaces the current object with another object.
Description:
The call method can be used to call a method instead of another object. The call method changes the object context of a function from the initial context to the new object specified by thisObj.
If the thisObj parameter is not provided, the Global object is used as thisObj.
apply method:
Syntax: apply(thisObj, [argArray])
Definition: Apply a method of a certain object and replace the current object with another object.
Note:
If argArray is not a valid array or is not an arguments object, a TypeError will be caused.
If neither argArray nor thisObj is provided, the Global object will be used as thisObj and no parameters can be passed.
eg1:
var pet={ words:'...', speak:function(say){ console.log(say+' '+this.words) } }var dog={ words:'Wang'} pet.speak.call(dog,'speak') //speak Wang
eg2
function Pet(word){ this.word=word; this.speak=function(){ console.log(this.word) } }function Dog(word){ Pet.call(this,word) //Pet.apply(this,arguments); 二者选其一即可}var dog=new Dog('Wang'); dog.speak(); //Wang
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to the php Chinese websiteOthersRelated article!
Recommended reading:
Detailed explanation of javaScript objects
The above is the detailed content of javaScript uses call and apply. For more information, please follow other related articles on the PHP Chinese website!