原型式继承
道格拉斯·克罗克福德在2006年写了一篇文章, 在该文章中介绍了一种实现继承的方法, 即原型式继承。实现如下:
function object(o) { function F() {} F.prototype = o; return new F(); }
使用方式如下:
var person = { name : "Nicholas", colors : ["red", "blue", "green"] } var obj = object(person); console.log(obj.name); //"Nicholas" console.log(obj.colors); //"red", "blue", "green"
要求就是必须有一个对象作为另一个对象的基础。 和原型链模式类似,原型链模式是用超类的实例对象重写子类的原型对象,而原型式模式则是通过传入的对象重写目标对象的原型对象。
ECMAScript通过新增Object.create()方法规范化了原型式继承。这个方法接收两个参数:一个作为新对象原型的对象和一个为新定义额外属性的对象。在传入一个参数的情况下,Object.create()与object()方法的行为相同。
使用一个参数:
var person = {
name : "Nicholas",
friends : ["Shelly", "Court", "Van"]
};
var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
var yetAnotherPerson = Object.create(person);
yetAnotherPerson.name = "Lina";
yetAnotherPerson.friends.push("Barbie");
console.log(person.friends); //"Shelly", "Court", "Van", "Rob", "Barbie"
console.log(person.name); //"Nicholas"
console.log(anotherPerson.name); //"Greg"
console.log(yetAnotherPerson.name); //"Lina"
输出结果: 因为friends属性时引用数据类型,且person对象是作为anotherPerson对象和yetAnotherPerson对象的原型,所以在anotherPerson对象和yetAnotherPerson对象对friends对象做的修改会体现在person对象的friends上。
使用两个参数:
Object.create方法的第二个参数和Object.defineProperties()方法的第二个参数相同。
var person = { name : "Nicholas", friends : ["Shelly", "Court", "Van"] }; var anotherPerson = Object.create(person, { name : { value : "Greg" } }); console.log(anotherPerson.name);
备注: 例子及截图均来自《JAVASCRIPT高级程序设计:第3版》