Appearance
寄生式继承
本节目标:理解“寄生式继承”的核心思路,并能把它用于实际开发或面试表达。 寄生式(
parasitic)继承是与原型式继承紧密相关。
就是寄生在一个已经拥有我们需要属性的对象上,再稍做修改得到我们所要的对象。 寄生式继承也是用来拓展原生构造函数原型上的方法。但又不会修改原生构造函数原型对象。
**区别:**封装了一个函数,并在函数的内部以某种方式来增强对象,然后再像真的做了所有工作一样返回对象。如下: function createAnother(origin) { //通过调用构造函数创建了一个新对象 var clone = object(origin); //以某种方式来增强这个对象 clone.sayHi = function () { console.log('hi'); }; //返回了这个对象 return clone; }
使用: var person = { name: 'Nicholas', firends: ['Shelby', 'Court', 'Van'] }; var anotherPerson = createAnother(person); console.log(anotherPerson.sayHi);//'hi'
示例2 function createObject(o) { function F() {} F.prototype = o; return new F(); } function createChild(parent) { const child = createObject(parent); child.sayHi = function() { console.log('Hi from Child'); }; return child; } const parent = { name: 'Parent', sayHello: function() { console.log('Hello from Parent'); } }; const child = createChild(parent); console.log(child.name); // 输出: Parent child.sayHello(); // 输出: Hello from Parent child.sayHi(); // 输出: Hi from Child
在主要考虑对象而不是自定义类型和构造函数的情况下,寄生式继承是一种有用的模式。前面示范继承模式时使用的object()函数不是必需的;任何能够返回新对象的函数都适用于此模式。
寄生式继承问题 寄生式继承如果为对象增加方法,会由于不能做到对象方法的复用而降低效率;
