JS面向对象中,继承相对是比较难的,即便看了不少文章,可能依然不明白,下面我谈谈个人理解。函数
1.构造函数继承优化
function p0(){this
this.name = "p0";prototype
this.colors = ["pink","black","gray"];}对象
function children0(){blog
p0.call( this );继承
this.type = "children0";}原型链
经过这种在子类中执行父类的构造函数调用,把父类构造函数的this指向为子类实例化对象引用,从而致使父类执行的时候父类里面的属性都会被挂载到子类的实例上去。原型
new children0().name; // p0io
new children0().colors; // ["pink","black","gray"]
这种方式,父类原型上的东西无法继承,所以函数复用也就无从谈起
p0.prototype.sex = "男";
p0.prototype.say = function() {
console.log(" hellow");}
new children0().sex; // undefined
// Uncaught TypeError: (intermediate value).say is not a function
new children0().say();
缺点:children0没法继承p0的原型对象,只能算是部分继承
2.原型链式继承
function p1(){
this.name = "p1";
this.colors = ["red","blue","yellow"];
}function Children1(){
this.name = "Children1";}
Children1.prototype = new p1();
p1.prototype.sex = "女";
p1.prototype.say = function() {
console.log(" hellow! ");}
new Children1().sex; // 女
new Children1().say(); //hellow!
这种方式确实解决了上面借用构造函数继承方式的缺点。
可是,这种方式仍有缺点,以下:
var s1 = new Children1();
s1.colors.push("black");
var s2 = new Children1();
s1.colors; // (4) ["red", "blue", "yellow", "balck"]
s2.colors; // (4) ["red", "blue", "yellow", "balck"]
在这里实例化了两个Children1,s1中为父类的colors属性push了一个颜色black,可是s2也改变了。由于原型对象是共用的。
但咱们并不想这样,这是这个方法缺点。
3.组合式继承
意思就是把构造函数和原型链继承结合起来。
function p2(){
this.name = "p2";
this.colors = ["red","blue","yellow"];}
function Children2(){
p2.call(this);
this.type = "Children2";}
Children2.prototype = new p2()
var s1 = new Children2();
s1.colors.push("black");
var s2 = new Children2();
s1.colors; // (4) ["red", "blue", "yellow", "balck"]
s2.colors; // (3) ["red", "blue", "yellow"]
能够看到,s2和s1两个实例对象已经被隔离了。
但这种方式仍有缺点。父类的构造函数被执行了两次,第一次是Children2.prototype = new p2(),第二次是在实例化的时候,这是没有必要的。
组合式继承优化1
直接把父类的原型对象赋给子类的原型对象
function p3(){
this.name = "p3";
this.colors = ["red","blue","yellow"];}
p3.prototype.sex = "男";
p3.prototype.say = function(){console.log("Oh, My God!")}
function Children3(){
p3.call(this);
this.type = "Children3";}
Children3.prototype = p3.prototype;
var s1 = new Children3();
var s2 = new Children3();
console.log(s1, s2);
可是,看以下代码:
console.log(s1 instanceof Child3); // true
console.log(s1 instanceof Parent3); // true
能够看到,咱们没法区分实例对象s1究竟是由Children3直接实例化的仍是p3直接实例化的。用instanceof关键字来判断是不是某个对象的实例就基本无效了。
咱们还能够用.constructor来观察对象是否是某个类的实例:
console.log(s1.constructor.name); // p3
能够看出,s1的构造函数是父类,而不是子类Children3,这并非咱们想要的。
组合式继承优化2
function p4(){
this.name = "p4";
this.colors = ["red","blue","yellow"];}
p4.prototype.sex = "男";
p4.prototype.say = function(){console.log("Oh, My God!")}
function Children4(){
p4.call(this);
this.type = "Children4";}
Children4.prototype=Object.create(p4.prototyp;
Children4.prototype.constructor = Children4;
Object.create是一种建立对象的方式,它会建立一个中间对象
var p = {name: "p"}
var obj = Object.create(p)
// Object.create({ name: "p" })
经过这种方式建立对象,新建立的对象obj的原型就是p,同时obj也拥有了属性name,这个新建立的中间对象的原型对象就是它的参数。
这种方式解决了上面的全部问题,是继承的最好实现方式。