这个题目编辑了好久,一直都没来聊一聊。下面聊一下我理解的继承方法。
1.原型链继承
var Animal = function () { this.type = []; }; var Cat = function () { }; Cat.prototype = new Animal(); var cat1 = new Cat(); cat1.type.push("cat1"); var cat2 = new Cat(); cat2.type.push("cat2"); console.log(cat1.type); // ["cat1", "cat2"] console.log(cat2.type); // ["cat1", "cat2"]
可见原型链继承中引用类型值得原型属性会被所有实例共享。
2.构造函数继承
var Animal = function () { this.type = []; }; var Cat = function () { Animal.call(this); }; var cat1 = new Cat(); cat1.type.push("cat1"); var cat2 = new Cat(); cat2.type.push("cat2"); console.log(cat1.type); // ["cat1"] console.log(cat2.type); // ["cat2"]
构造函数继承虽然解决了上面的问题,但是每个实例会重新new一下方法,不会共享方法。
3.组合继承
var Animal = function (name) { this.name = name; this.type = []; }; Animal.prototype.sayName = function () { console.log(this.name); }; var Cat = function (name, voice) { Animal.call(this, name); this.voice = voice; }; Cat.prototype = new Animal(); Cat.prototype.say = function () { console.log(this.voice); }; var cat1 = new Cat("小花", "喵喵1"); cat1.type.push("cat1"); var cat2 = new Cat("小红", "喵喵2"); cat2.type.push("cat2"); console.log(cat1.type); // ["cat1"] console.log(cat2.type); // ["cat2"] cat1.sayName(); // 小花 cat1.say(); // 喵喵1 cat2.sayName(); // 小红 cat2.say(); // 喵喵2
组合继承融合了原型和构造函数组合继承的优势,实现了属性私有,方法共享。是最常用的继承方式。