现在的位置: 首页 > 综合 > 正文

javascript 对象基础 继承机制实例 call() apply 方法!

2013年02月16日 ⁄ 综合 ⁄ 共 775字 ⁄ 字号 评论关闭

call() 方法

它的第一个参数用作this的对象,其他参数都直接传递给函数自身;

重写上个例子:

function ClassA(sColor){
this.color = sColor;
this.sayColor = function(){
alert(this.color)
}
};
function ClassB(sColor,sName){
ClassA.call(this,sColor)//这里的this 是指ClassB

this.name = sName;
this.sayName = function(){
alert(this.name);
}
}
var a = new ClassA("red");
var b = new ClassB("blue","idea");
a.sayColor();
b.sayColor();
b.sayName();

apply() 方法

apply() 方法有两个参数,用作 this 的对象和要传递给函数的参数的数组.

重写上面的例子:

function ClassA(sColor,sName){
this.color = sColor;
this.sayColor = function(){
alert(sMsg + " " + this.color)
}
};
function ClassB(sColor,sName){
ClassA.apply(this,[sColor,sName])
//ClassA.apply(this,arguments) 可使用 arguments 对象
this.name = sName;
this.sayName = function(){
alert(this.name);
}
}
var a = new ClassA("red","sun color is");
var b = new ClassB("blue","idea");
a.sayColor();
b.sayColor();
b.sayName();

抱歉!评论已关闭.