借助原型可以基于已有的对象创建新对象,同时还不必因此创建自定义类型。
function object(o){
function F(){}
F.prototype = o;
return new F();
}
在 object()函数内部,①创建了一个临时性的构造函数,②将传入的对象作为这个构造函数的原型,③返回了这个临时类型的一个新实例。从本质上讲,object()对传入其中的对象执行了一次浅复制。
首先看一下下面的代码段,来理解一下object(o)这个函数
<script>
function object(o){
function F(){}
F.prototype = o;
return new F();
}
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = object(person);
console.log(anotherPerson)
</script>
控制台打印
然后画一画原型链,就明白为什么了
var person = {
name: "Nicholas",
friends: ["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");
alert(person.friends); //"Shelby,Court,Van,Rob,Barbie"
这意味着 person.friends 不仅属于 person 所有,而且也会被 anotherPerson以及 yetAnotherPerson 共享。实际上,这就相当于又创建了 person 对象的两个副本。
ECMAScript 5 的 Object.create() 方法规范化了原型式继承。这个方法接收两个参数:一个用作新对象原型的对象和(可选的)一个为新对象定义额外属性的对象。在传入一个参数的情况下,Object.create() 与 object() 方法的行为相同。
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
var yetAnotherPerson = Object.create(person);
yetAnotherPerson.name = "Linda";
yetAnotherPerson.friends.push("Barbie");
alert(person.friends); //"Shelby,Court,Van,Rob,Barbie"
继续看下面的代码段
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = Object.create(person);
anotherPerson.name = "Greg";
anotherPerson.friends.push("Rob");
console.log(anotherPerson);
首先先看一下下面的代码段
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = Object.create(person);
console.log("Object.create---------------");
console.log(anotherPerson)
打印出来
和object函数的效果一模一样
Object.create() 如果加上第二个参数,则会覆盖原型上的同名属性
var person = {
name: "Nicholas",
friends: ["Shelby", "Court", "Van"]
};
var anotherPerson = Object.create(person, {
name: {
value: "Greg"
}
});
console.log(anotherPerson);
alert(anotherPerson.name); //"Greg"
上面代码控制台会打印,就会知道为什么说是覆盖了
如果只想让一个对象与另一个对象保持类似的情况下,原型式继承是完全可以胜任的。不过别忘了,包含引用类型值的属性始终都会共享相应的值,就像使用原型模式一样。