call和apply

call方法

call([thisObj[,arg1[, arg2[, [,.argN]]]]])
調(diào)用一個對象的方法,以另一個對象替換當(dāng)前對象
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) ,所以運行結(jié)果為:alert(4); // 注意:js 中的函數(shù)其實是對象,函數(shù)名是對 Function 對象的引用。

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

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

//通過call或apply方法,將原本屬于Animal對象的showName()方法交給對象cat來使用了。
//輸入結(jié)果為"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);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容