原型式继承的思想是借用原型可以基于已有的对象创建新对象,同时还不必因此创建自定义类型。
为了达到这个目的,给出如下函数:
function object(o){
function F(){}
F.prototype = o;
return new F();
}
在object()函数内部,先创建一个临时性的构造函数,将传入的对象作为这个构造函数的原型,最后返回这个函数的新实例。说白了,就是对传入的对象执行一个浅复制,也就是说将创建的新对象F的原型对象指向o(我是这么理解滴)。
function object(o){
function F(){}
F.prototype = o;
return new F();
}
var person = {
name: "Nico",
friends: ["Shlby","huu","dima"]
};
var anotherPerson = object(person);
//var anotherPerson = Object.create(person);
anotherPerson.name = "Greg"; //为实例添加自身属性以覆盖原型对象上的同名属性
anotherPerson.friends.push("rob");
var yetanotherPerson = object(person);
// var yetanotherPerson = Object.create(person);
yetanotherPerson.name = "Linda";
yetanotherPerson.friends.push("Barbie");
alert(anotherPerson.name); //Greg
alert(anotherPerson.friends); //Shlby,huu,dima,rob,Barbie
alert(yetanotherPerson.name); //Linda
alert(yetanotherPerson.friends); //Shlby,huu,dima,rob,Barbie
alert(person.name); //Nico
alert(person.friends); //Shlby,huu,dima,rob,Barbie
这种原型式继承,要求你必须有一个对象可以作为另一个对象的基础。有这么一个对象的话,可以把它传给object()函数,再根据具体的需求对得到的对象加以修改即可(比如anotherPerson.name="Greg")。
在这个例子中,可以作为另一个对象基础的是person对象,于是把它传入object()函数中,然后该函数会返回一个新对象,这个对象将person作为原型,所以它的原型中就包含一个基本类型值属性和一个引用类型值属性。这意味着person.friends不仅属于person所有,而且也会被anotherPerson和yetAnotherPerson共享。实际上,这就相当于又创建了person对象的两个副本。
ECMAScript5新增了Object.create()规范了原型式继承,这个方法接受两个参数:一个用作新对象原型的对象和(可选的)一个为新对象定义额外属性的对象。在传入一个参数的情况下,Object.create()和object()方法的行为相同。如上被注释的代码。
Object.create()方法的第二个参数与Object.defineProperties()方法的第二个参数格式相同:每个属性都是通过自己的描述符定义的。以这种方式指定的任何属性都会覆盖原型对象上的同名属性。
例如:
var person ={
name:"Nico",
friends:["Shelby","Court","Van"]
}
var anotherPerson = Object.create(person,{
name:{
value:"Greg"
}
});
alert(anotherPerson.name); //Greg
支持Object.create()方法的浏览器有:IE 9+,FF 4+,Safari 5+,Opera 12+,Chrome.
在没必要兴师动众地创建构造函数,只是想让一个对象与另一个对象保持类似的情况下,可以采用原型式继承。不过记住,包含引用类型值的属性始终会被实例共享,就像使用原型模式一样。