JS面向对象编程基础篇(三)面向对象编程基础篇(三) 继承操作实例详解继承操作实例详解
本文实例讲述了JS面向对象编程继承操作。分享给大家供大家参考,具体如下:
构造函数的继承构造函数的继承
上一篇JS面向对象编程封装操作,主要介绍了如何”封装”数据和方法,以及如何从原型对象生成实例。
今天要介绍的是,对象之间的对象之间的”继承继承”的五种方法的五种方法。
比如,现在有一个”动物”对象的构造函数。
function Animal(){
this.species = "动物";
this.action="吃"
}
还有一个”猫”对象的构造函数。
function Cat(name,color){
this.name = name;
this.color = color;
}
怎样才能使”猫”继承”动物”呢?
一、一、 构造函数绑定构造函数绑定
第一种方法也是最简单的方法,使用call或apply方法,将父对象的构造函数绑定在子对象上,即在子对象构造函数中加一行:
function Cat(name,color){
Animal.apply(this, arguments);
this.name = name;
this.color = color;
}
var cat1 = new Cat("大毛","黄色");
console.log(cat1.species); // 动物
console.log(cat1.action); // 吃
二、二、 prototype模式模式
第二种方法更常见,使用prototype属性。
如果”猫”的prototype对象,指向一个Animal的实例,那么所有”猫”的实例,就能继承Animal了。
Cat.prototype = new Animal();
Cat.prototype.constructor = Cat;
var cat1 = new Cat("大毛","黄色");
console.log(cat1.species); // 动物
console.log(cat1.action); // 吃
代码的第一行,我们将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。
console.log(Cat.prototype.constructor == Animal); //true