call和apply

call方法

call([thisObj[,arg1[, arg2[, [,.argN]]]]])
调用一个对象的方法,以另一个对象替换当前对象
function add(a,b)
{
alert(a+b);
}
function sub(a,b)
{
alert(a-b);
}

add.call(sub,3,1);
function Animal(){
this.name = "Animal";
this.showName = function(){
alert(this.name);
}
}
这个例子中的意思就是用 add 来替换 sub,add.call(sub,3,1) == add(3,1) ,所以运行结果为:alert(4); // 注意:js 中的函数其实是对象,函数名是对 Function 对象的引用。

function Cat(){
this.name = "Cat";
}

var animal = new Animal();
var cat = new Cat();

//通过call或apply方法,将原本属于Animal对象的showName()方法交给对象cat来使用了。
//输入结果为"Cat"
animal.showName.call(cat,",");

多重继承

function Class10()
{
this.showSub = function(a,b)
{
alert(a-b);
}
}

function Class11()
{
this.showAdd = function(a,b)
{
alert(a+b);
}
}

function Class2()
{
Class10.call(this);
Class11.call(this);
}

apply

1.apply示例:

<script type="text/javascript">
function Person(name,age) {
this.name=name; this.age=age;
}
functionStudent(name,age,grade) {
Person.apply(this,arguments); this.grade=grade;
}
var student=new Student("qian",21,"一年级");
alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容