【发布时间】:2014-01-08 11:55:21
【问题描述】:
我正在扩展 Object.create() 以获取第二个参数,例如
if (typeof Object.create !== 'function') {
Object.create = function (o,arg) {
function F() {}
F.prototype = o;
return new F(arg);
};
}
//could be multiple of these objects that hold data
var a = {
b : 2
};
var c = function(data){
return{
d : Object.create(data)
};
};
//create new instance of c object and pass some data
var newObj = function(arg){
return(Object.create(c(arg)))
}
var e = newObj(a);
e.d.b = 5;
var f = newObj(a);
console.log(e.d.b);
console.log(f.d.b);
我只是想知道以这种方式使用Object.create() 是否有任何陷阱?如果我要使用它,我会对 Object.create() 函数中的 arg 参数做一些额外的检查,但重点是要找出这是否会导致任何问题或过度杀伤等。
【问题讨论】:
-
Crockford's Prototypal inheritance - Issues with nested objects 的可能副本。在您的情况下,继承
c()的返回对象没有多大意义,因为d属性已经是唯一的。
标签: javascript oop object-create