串门回来难得的休息一会,我们来看看object的方法:
Object.create这个方法会使用指定的原型对象及其属性去创建一个新的对象。
用法:
Object.create(proto[, propertiesObject])
返回值是:在指定原型对象上添加新属性后的对象。(如果proto的参数不是null或者一个对象,那么他就会抛出一个TypeError)
function Parent(){}
Parent.prototype.hello=function () {
console.log("我是来自父类的");
}
function Child(){
Parent.call(this);
}
//子类继承父类;
Child.prototype=Object.create(Parent.prototype);
Child.prototype.constructor=Child;
var test=new Child();
console.log(test instanceof Child);
console.log(test instanceof Parent);
console.log(test.hello())
上面的例子中我们定义了一个Parent函数,又定义了一个以他为原型的child函数。上面的结果是true true ,“我是来自父类的”。里面的子类继承父类用到了本文的object.create;
同样的我们还可以创建一个原型为空的对象:
var o=Object.create(null);
下面我们用Object.create来创建一个有属性的对象,因为这个方法的第二属性是可没有的,所以说上述的例子中没有用到。
o=Object.create(Object.prototype,{
// foo会成为所创建对象的数据属性
foo: {
writable:true,
configurable:true,
value: "hello"
},
// bar会成为所创建对象的访问器属性
bar: {
configurable: false,
get: function() { return 10 },
set: function(value) {
console.log("Setting:", value);
}
}
})
这个方法的用处也就可想而知了,最后还有一个例子:
function Constructor(){}
o = new Constructor();
// 上面的一句就相当于:
o = Object.create(Constructor.prototype);
// 当然,如果在Constructor函数中有一些初始化代码,Object.create不能执行那些代码