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

来源:互联网 发布:如何生成淘宝口令 编辑:程序博客网 时间:2024/05/17 06:05

摘自: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();