1, call() and apply() are used to change this points to, the difference is that the parameter list is different(The former is a continuous parameter, the latter is a parameter array)
2, method definition:
function.apply(thisObj[, argArray]) function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);
Specially, when no parameters are passed, function.call() is quite To execute this function
3, example:
Because apply() and # The ##call() methods have the same effect, so here we take call() as an example, apply() Similarly:
//定义一个Car的构造函数 function Car(name,height){ this.name=name; this.height=height; } function Maserati(name,age,height,width){ this.name=name; this.age=age; this.height=height; this.width=width; } 可以发现这里函数2包含了函数1的所有属性,即是继承的意思 因此函数2这里可以用call()方法改写成 function Maserati(name,age,height,width){ Car.call(this,name,age);//此处this就是指向Maserati,此时Maserati就拥有Car的所有属性和方法了。 this.height=height; this.width=width; } var a=new Maserati("maserati",23,188,98);
The above is the detailed content of Usage of call(), apply(). For more information, please follow other related articles on the PHP Chinese website!