Prototypal Inheritance

Object.create(obj) 以obj为原型创造实例

  1. let person = {
  2. name: "Nicholas",
  3. friends: ["Shelby", "Court", "Van"]
  4. };
  5. let anotherPerson = Object.create(person);
  6. anotherPerson.name = "Greg";
  7. anotherPerson.friends.push("Rob");
  8. let yetAnotherPerson = Object.create(person);
  9. yetAnotherPerson.name = "Linda";
  10. yetAnotherPerson.friends.push("Barbie");
  11. console.log(person.friends); // "Shelby,Court,Van,Rob,Barbie"

Object.create()可以传第二个参数,和Object.defineProperties()一样,给实例添加属性

  1. let person = {
  2. name: "Nicholas",
  3. friends: ["Shelby", "Court", "Van"]
  4. };
  5. let anotherPerson = Object.create(person, {
  6. name: {
  7. value: "Greg"
  8. }
  9. });
  10. console.log(anotherPerson.name); // "Greg"

image.png

Parasitic(寄生) Inheritance

用一个函数返回一个对象

  1. function createAnother(original){
  2. let clone = object(original); // create a new object by calling a function
  3. clone.sayHi = function() { // augment the object in some way
  4. console.log("hi");
  5. };
  6. return clone; // return the object
  7. }
  8. let person = {
  9. name: "Nicholas",
  10. friends: ["Shelby", "Court", "Van"]
  11. };
  12. let anotherPerson = createAnother(person);
  13. anotherPerson.sayHi(); // "hi"

寄生式组合继承

  1. function inheritPrototype(subType, superType) {
  2. let prototype = object(superType.prototype);
  3. // 创建父类原型的一个副本
  4. prototype.constructor = subType;
  5. // 增强对象
  6. subType.prototype = prototype;
  7. // 赋值对象
  8. }
  9. function SuperType(name) {
  10. this.name = name;
  11. this.colors = ["red", "blue", "green"];
  12. }
  13. SuperType.prototype.sayName = function() {
  14. console.log(this.name);
  15. };
  16. function SubType(name, age) {
  17. SuperType.call(this, name);
  18. this.age = age;
  19. }
  20. inheritPrototype(SubType, SuperType);
  21. SubType.prototype.sayAge = function() {
  22. console.log(this.age);
  23. };