四.原型式繼承(Object.create)this
let parent4 = { name: "parent4", friends: ["p1", "p2", "p3"], getName: function() { return this.name; } }; let person4 = Object.create(parent4); person4.name = "tom"; person4.friends.push("jerry"); let person5 = Object.create(parent4); person5.friends.push("lucy"); console.log(person4.name); // tom console.log(person4.name === person4.getName()); // true console.log(person5.name); // parent4 console.log(person4.friends); // ["p1", "p2", "p3","jerry","lucy"] console.log(person5.friends); // ["p1", "p2", "p3","jerry","lucy"]
缺點:淺拷貝,多個實例的引用類型屬性指向相同的內存prototype
五. 寄生式繼承code
let parent5 = { name: "parent5", friends: ["p1", "p2", "p3"], getName: function() { return this.name; } }; function clone(original) { let clone = Object.create(original); clone.getFriends = function() { return this.friends; }; return clone; } let person5 = clone(parent5); let person6 = clone(parent5); person5.name = '22'; person5.friends.push(22); console.log(person5.getName()); // parent5 console.log(person5.getFriends()); // ["p1", "p2", "p3", 22] console.log(person6.getName()); // parent5 console.log(person6.getFriends()); // ["p1", "p2", "p3", 22]
缺點:淺拷貝,多個實例的引用類型屬性指向相同的內存繼承
六.寄生組合式繼承 (全場最佳)內存
function clone (parent, child) { // 這裏改用 Object.create 就能夠減小組合繼承中多進行一次構造的過程 child.prototype = Object.create(parent.prototype); child.prototype.constructor = child; } function Parent6() { this.name = 'parent6'; this.play = [1, 2, 3]; } Parent6.prototype.getName = function () { return this.name; } function Child6() { Parent6.call(this); this.friends = 'child5'; } clone(Parent6, Child6); Child6.prototype.getFriends = function () { return this.friends; } let person6 = new Child6(); console.log(person6); //{friends:"child5",name:"child5",play:[1,2,3],__proto__:Parent6} console.log(person6.getName()); // parent6 console.log(person6.getFriends()); // child5