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