对象的继承

在其他语言中,例如 java C# C++等强类型的语言,都会有一个extend关键字达到继承的实现,但是js没有这个extend这个方法,只有原型原型链,那我们怎么去实现继承?

比如,现在有一个"动物"对象的构造函数。

  
function Animal(){     this.species = "动物";   }

 

还有一个"猫"对象的构造函数。

 
 function Cat(name,color){  
   this.name = name;    
 this.color = color;   }

 

怎样才能使"猫"继承"动物"呢?

1. 构造函数绑定

第一种方法也是最简单的方法,使用call或apply方法,将父对象的构造函数绑定在子对象上,即在子对象构造函数中加一行:

function Cat(name,color){
    Animal.apply(this, arguments);
    this.name = name;
    this.color = color;
  }
  var cat1 = new Cat("大毛","黄色");
  alert(cat1.species); // 动物

call方法:

语法:call([thisObj[,arg1[, arg2[, [,.argN]]]]])

定义:调用一个对象的一个方法,以另一个对象替换当前对象。

说明: call 方法可以用来代替另一个对象调用一个方法。call 方法可将一个函数的对象上下文从初始的上下文改变为由 thisObj 指定的新对象。 如果没有提供 thisObj 参数,那么 Global 对象被用作 thisObj。

apply方法:

语法:apply([thisObj[,argArray]])

定义:应用某一对象的一个方法,用另一个对象替换当前对象。

说明: 如果 argArray 不是一个有效的数组或者不是 arguments 对象,那么将导致一个 TypeError。 如果没有提供 argArray 和 thisObj 任何一个参数,那么 Global 对象将被用作 thisObj, 并且无法被传递任何参数。

 

 

2. prototype模式

第二种方法更常见,使用prototype属性。

如果"猫"的prototype对象,指向一个Animal的实例,那么所有"猫"的实例,就能继承Animal了。

  
 Cat.prototype = new Animal();
  Cat.prototype.constructor = Cat;
  var cat1 = new Cat("大毛","黄色");
  alert(cat1.species); // 动物

 

代码的第一行,我们将Cat的prototype对象指向一个Animal的实例。

 
 Cat.prototype = new Animal();

 

它相当于完全删除了prototype 对象原先的值,然后赋予一个新值。但是,第二行又是什么意思呢?

  
Cat.prototype.constructor = Cat;

 

原来,任何一个prototype对象都有一个constructor属性,指向它的构造函数。如果没有"Cat.prototype = new Animal();"这一行,Cat.prototype.constructor是指向Cat的;加了这一行以后,Cat.prototype.constructor指向Animal

alert(Cat.prototype.constructor == Animal); //true

 

更重要的是,每一个实例也有一个constructor属性,默认调用prototype对象的constructor属性。

alert(cat1.constructor == Cat.prototype.constructor); // true

 

因此,在运行"Cat.prototype = new Animal();"这一行之后,cat1.constructor也指向Animal

3. 拷贝继承

上面是采用prototype对象,实现继承。我们也可以换一种思路,纯粹采用"拷贝"方法实现继承。简单说,如果把父对象的所有属性和方法,拷贝进子对象,不也能够实现继承吗?这样我们就有了第三种方法。

首先,还是把Animal的所有不变属性,都放到它的prototype对象上。

  
function Animal(){}   Animal.prototype.species = "动物";

 

然后,再写一个函数,实现属性拷贝的目的。

 function extend(Child, Parent) {
    var p = Parent.prototype;
    var c = Child.prototype;
    for (var i in p) {
      c[i] = p[i];
      }
  }

 

posted @ 2017-08-13 10:41  哈哈敲敲  阅读(141)  评论(0编辑  收藏  举报