理解js对象继承的N种模式(2)

var SuperType = { name: "Oliver", number: [321,321,4532,1] }; var SubType1 = Object.create(SuperType,{ name: { value : "Troy" } }); var SubType2 = Object.create(SuperType,{ name: { value : "Alice" } }); SubType1.number.pop(); SubType2.number.pop(); console.log(SubType1.name + SubType2.name + SubType1.number + SubType2.number + SuperType.name + SuperType.number); //TroyAlice321,321321,321Oliver321,321

寄生式继承(用于共享引用类型的值,与原型式类似)

function createAnother(original){ var clone = Object(original); clone.sayHi = function(){ return "Hi"; }; return clone; } var person = { name: "Oliver", number: [13,21,31,1] }; var anotherPerson = createAnother(person); anotherPerson.number.pop(); console.log(anotherPerson.sayHi() + anotherPerson.number); //Hi13,21,31 console.log(person.number); //13,21,31

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwggw.html