Prototypal Inheritance
Object.create(obj) 以obj为原型创造实例
let person = {name: "Nicholas",friends: ["Shelby", "Court", "Van"]};let anotherPerson = Object.create(person);anotherPerson.name = "Greg";anotherPerson.friends.push("Rob");let yetAnotherPerson = Object.create(person);yetAnotherPerson.name = "Linda";yetAnotherPerson.friends.push("Barbie");console.log(person.friends); // "Shelby,Court,Van,Rob,Barbie"
Object.create()可以传第二个参数,和Object.defineProperties()一样,给实例添加属性
let person = {name: "Nicholas",friends: ["Shelby", "Court", "Van"]};let anotherPerson = Object.create(person, {name: {value: "Greg"}});console.log(anotherPerson.name); // "Greg"
Parasitic(寄生) Inheritance
用一个函数返回一个对象
function createAnother(original){let clone = object(original); // create a new object by calling a functionclone.sayHi = function() { // augment the object in some wayconsole.log("hi");};return clone; // return the object}let person = {name: "Nicholas",friends: ["Shelby", "Court", "Van"]};let anotherPerson = createAnother(person);anotherPerson.sayHi(); // "hi"
寄生式组合继承
function inheritPrototype(subType, superType) {let prototype = object(superType.prototype);// 创建父类原型的一个副本prototype.constructor = subType;// 增强对象subType.prototype = prototype;// 赋值对象}function SuperType(name) {this.name = name;this.colors = ["red", "blue", "green"];}SuperType.prototype.sayName = function() {console.log(this.name);};function SubType(name, age) {SuperType.call(this, name);this.age = age;}inheritPrototype(SubType, SuperType);SubType.prototype.sayAge = function() {console.log(this.age);};
