面向对象编程 -- 继承3
一、原型式继承
// 一种不涉及严格意义上构造函数的继承方法。
// 出发点是即使不自定义类型也可以通过原型实现对象之间的信息共享。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
let person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
let anotherPerson = object(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
let yetAnotherPerson = object(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
console.log(person.friends); // "Shelby,Court,Van,Rob,Barbie"

// ECMAScript 5 通过增加 object.create() 方法将原型式继承的概念规范化。
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.creact() 的第二个参数与 Object.defineProperties() 的第二个参数一样:每个新增属性都通过各自的描述。
let person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
let anotherPerson = Object.create(person, {
name: {
value: "Greg"
}
});
console.log(anotherPerson.name); // "Greg"

二、寄生式继承
// 与原型式继承比较接近的一种继承方式是寄生式继承
// 创建一个实现继承的函数,以某种方式增强对象,然后返回这个对象。
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
function createAnother(original){
let clone = object(original); // 通过调用函数创建新对象
clone.sayHi = function() { // 以某种方式扩充对象
console.log("hi");
};
return clone; // 返回这个对象
}
let person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
let anotherPerson = createAnother(person);
anotherPerson.sayHi(); // "hi"
