您的位置:首页 > 移动开发

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

2012-01-09 14:45 1271 查看
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();
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: