美文网首页
call和apply

call和apply

作者: a180754bf396 | 来源:发表于2017-09-19 20:15 被阅读0次

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);

相关文章

网友评论

      本文标题:call和apply

      本文链接:https://www.haomeiwen.com/subject/ldegsxtx.html