时间:2021-07-01 10:21:17 帮助过:26人阅读
2、方法定义:
function.apply(thisObj[, argArray])
function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);特别地,当没有传参数时,function.call() 相当于执行这个function
3、实例:
由于apply()和call()方法作用是一致的,因此这里以call()为例,apply()同理:
//定义一个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);得到如下结果:

以上就是call(),apply()的用法的详细内容,更多请关注Gxl网其它相关文章!