JS继承与重载

js学习笔记(类的继承、重载)
2009-03-29 17:19

[b]一、对象冒充[/b]:构造函数使用this关键字给所有属性和方法赋值。因为构造函数只是一个函数,所以可以使用ClassA的构造函数成为ClassB的方法,然后调用它,ClassB就会收到ClassA的构造函数中定义的属性和方法。但需要注意的是,当继承生成新的方法使用后应当删除,不至影响新的方法的创建。
[b]1>普通对象冒充:[/b]
如:
function ClassA(sColor){
this.color = sColor;
this.sayColor = function(){
alert(this.color);
};
}

function ClassB(sColor){
this.newMethod = ClassA;
this.newMethod(sColor);
delete this.newMethod;
}


[b]2>call()方法[/b]:call(obj,var1,var2,……);call的第一个参数用途this,其它的参数传递给函数本身;
如:

function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name = sName;
this.sayName = function (){
alert(this.name);
};
}


[b]3>apply()方法[/b]:apply(obj,arr),第一个参数是用作this的参数,第二个参数是一个传递给函数的参数的数组。
如:
function ClassB(sColor,sName){
ClassA.apply(this, new Array(sColor));
this.name = sName;
this.sayName = function(){
alert (this.name);
}
}


[b]二、原型链[/b]:由于prototype对象的任何属性和方法都被传给那个类的所有实例,原型链利用利用这种功能来实现继承机制。
如:
function ClassA(){}
ClassA.prototype.color = "red";
ClassA.prototype.sayColor = function(){
alert(this.color);
};

function ClassB(){}
ClassB.prototype = new ClassA();
ClassB.name = "";
ClassB.prototype.sayName = function (){
alert(this.name);
}


[b]三、混合方式[/b]:用对象冒充继承构造函数的属性,用原型链继承prototype对象的方法。
如:
function ClassA(sColor){
this.color = sColor;
}
ClassA.prototype.sayColor = function(){
alert(this.color);
}
function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name = sName;
}
ClassB.prototype = new ClassA();
ClassB.prototype.sayName = function(){
alert(this.name);
}


[b]四、利用zInherit库[/b]:zInherit库主要有两个方法用于继承;inheritFrom(class),用于复制class指定的类的所有属性和方法,但是不创建自身实例,也不重写prototype对象,以可以用于动态原型支持,同时也可以实现多重继承;这种方法在使用时需要引入zinherit.js文件;
如:
function ClassA(sColor){
this.color = sColor;
if(typeof ClassA._initialized == "undefined"){
ClassA.prototype.sayColor = function(){
alert(this.color);
}
ClassA._initialized = true;
}
}

function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name = sName;
if(typeof ClassB._initialized == "undefined"){
ClassB.prototype.inheritFrom(ClassA);
ClassB.prototype.sayName = function(){
alert(this.name);
}
ClassB._initialized = true;
}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值