在继承中常会出现两个问题:
父类的属性变成了子类的原型
构造器指向混乱
寄生组合式继承解决了这样的问题:
属性继承到属性
原型继承到原型
构造器指向明确
// 父类var Super = function(name) { this.name = name; this.friends = ["lily", "meimei"];};Super.PRototype.sayName = function() { console.log(this.name);};// 子类var Sub = function(name, age) { // 属性归到属性 Super.call(this, name); this.age = age;};// 原型归到原型Sub.prototype = Super.prototype;// 明确构造器Sub.prototype.constructor = Sub;Sub.prototype.sayAge = function() { console.log(this.age);};var sup1 = new Super("lucy", 18);var sub1 = new Sub("lily", 20); sub1.friends.push("poly");var sub2 = new Sub("poly", 2);
新闻热点
疑难解答