JavaScript中的面向对象----继承

摘自:http://www.cnblogs.com/LongWay/archive/2008/10/19/1314705.html

 

1、对象冒充

  1. function ClassA(sColor){
  2.     this.color = sColor;
  3.     this.sayColor = function(){
  4.         alert(this.color);
  5.     }
  6. }
  7. function ClassB(sColor,sName){
  8.     this.newMethod = ClassA;
  9.     this.newMethod(sColor);
  10.     delete this.newMethod;
  11.     
  12.     this.name = sName;
  13.     this.sayName = function(){
  14.         alert(this.name);
  15.     }
  16. }
  17. var objB = new ClassB("color of objB","name of objB");
  18. objB.sayColor();

 

2、call方法

  1. function ClassA(sColor){
  2.     this.color = sColor;
  3.     this.sayColor = function(){
  4.         alert(this.color);
  5.     }
  6. }
  7. function ClassB(sColor,sName){
  8. //    this.newMethod = ClassA;
  9. //    this.newMethod(sColor);
  10. //    delete this.newMethod;
  11.     ClassA.call(this,sColor);
  12.     
  13.     this.name = sName;
  14.     this.sayName = function(){
  15.         alert(this.name);
  16.     }
  17. }
  18. var objB = new ClassB("color of objB","name of objB");
  19. objB.sayColor();

 

3、apply方法

  1. function ClassA(sColor){
  2.     this.color = sColor;
  3.     this.sayColor = function(){
  4.         alert(this.color);
  5.     }
  6. }
  7. function ClassB(sColor,sName){
  8. //    this.newMethod = ClassA;
  9. //    this.newMethod(sColor);
  10. //    delete this.newMethod;
  11.     ClassA.apply(this,new Array(sColor));
  12.     
  13.     this.name = sName;
  14.     this.sayName = function(){
  15.         alert(this.name);
  16.     }
  17. }
  18. var objB = new ClassB("color of objB","name of objB");
  19. objB.sayColor();

 

4、原型链方法

  1. function ClassA(){
  2. }
  3. ClassA.prototype.color = "color";
  4. ClassA.prototype.sayColor = function(){
  5.     alert(this.color);
  6. }
  7. function ClassB(){
  8. }
  9. ClassB.prototype = new ClassA();
  10. ClassB.prototype.name = "name";
  11. ClassB.prototype.sayName = function(){
  12.     alert(this.name);
  13. }
  14. var objB = new ClassB();
  15. objB.color = "color of objB";
  16. objB.name = "name of objB";
  17. objB.sayColor();

 

5、混合方式

  1. function ClassA(sColor){
  2.     this.color = sColor;
  3. }
  4. ClassA.prototype.sayColor = function(){
  5.     alert(this.color);
  6. }
  7. function ClassB(sColor,sName){
  8.     ClassA.call(this,sColor);
  9.     this.name = sName;
  10. }
  11. ClassB.prototype = new ClassA();
  12. ClassB.prototype.sayName = function(){
  13.     alert(this.name);
  14. }
  15. var objB = new ClassB("color of objB","name of objB");
  16. objB.sayColor();
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值