原型的基本方法
Javascript提供了原型的相关方法来获取或设置原型prototype,如下:
(1)Object.create(proto[, descriptors]) :产生一个新的对象并设置proto为它的原型;
(2)Object.getPrototypeOf(obj) :返回对象obj的原型对象;
(3)Object.setPrototypeOf(obj, proto):设置对象obj的原型对象为proto;
下面是一个例子:
let animal = {
eats: true
};
// create a new object with animal as a prototype
let rabbit = Object.create(animal);
alert(rabbit.eats); // true
alert(Object.getPrototypeOf(rabbit) === animal); // get the prototype of rabbit
Object.setPrototypeOf(rabbit, {}); // change the prototype of rabbit to {}
Object.create(proto[, descriptors])的第二个参数是描述符,我们可以在该原型对象的基础上再添加一些属性,例如:
let animal = {
eats: true
};
let rabbit = Object.create(animal, {
jumps: {
value: true
}
});
alert(rabbit.jumps); // true
alert(rabbit.eats); //true
我们推荐使用Obejct.create()方法来复制一个对象,这种方式明显比for...in要好,例如:
// fully identical shallow clone of obj
let clone = Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj));
这种方式能够彻底地复制一个对象,包括被复制对象的所有属性:Symbol属性,数据属性和访问器属性等等