Appearance
原型式继承
本节目标:理解“原型式继承”的核心思路,并能把它用于实际开发或面试表达。 道格拉斯
·克罗克福在2006年提出了原型式继承(prototypal inheritance in JavaScript)。
就是把某个对象当成原型对象的继承方式,适合快速从已有对象获取属性和方法。
**思路:**只想让A对象与B对象保持类似的情况下,没必要兴师动众创建构造函数:
- 定义一个临时构造函数;
- 让临时构造函数的原型指向
B对象即可; - 然后返回临时构造函数的实例,即
A对象。
代码如下: function createObject(o) { function F() {} F.prototype = o; return new F(); } const parent = { name: 'Parent', sayHello: function() { console.log('Hello from Parent'); } }; const child = createObject(parent); console.log(child.name); // 输出: Parent child.sayHello(); // 输出: Hello from Parent
从本质上讲,object()对传入其中的对象执行了一次浅复制。看代码: var person = { name: 'Nicholas', firends: ['Shelby', 'Court', 'Van'] }; var anotherPerson = object(person); anotherPerson.name = 'Greg'; anotherPerson.friends.push('Rob'); var yetAnotherPerson = object(person); yetAnotherPerson.name = 'Linda'; yetAnotherPerson.friends.push('Barbie'); console.log(person.friends);//'Shelby,Court,Van,Rob,Barbie' person.friends属性,不仅person所有,而且也会被anotherPerson以及yetAnotherPerson共享,相当于又创建了person对象的两个副本。
Object.create() ECMAScript5通过新增Object.create()方法规范了原型式继承。 参数: 第一个参数是用作新对象原型的对象; 第二个参数是(可选的)一个为新对象定义额外属性的对象。与Object.defineProperties()方法的第二个参数格式相同:
- 每个属性都是通过自己的描述符定义的。
- 这种方式指定的任何属性都会覆盖原型对象上的同名属性。
例如: var person = { name: 'Nicholas', firends: ['Shelby', 'Court', 'Van'] }; var anotherPerson = Object.create(person, { name: { value: 'Greg' } }) console.log(anotherPerson.name);//'Greg'
