简体   繁体   English

在javascript中扩展Object.create()

[英]extending Object.create() in javascript

I'm extending Object.create() to take a second argument eg 我正在扩展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);

I'm just wondering if there are any pitfalls to using Object.create() in this way? 我只是想知道以这种方式使用Object.create()是否有任何陷阱? I would do some extra checking on the arg argument in the Object.create() function if I was to use this but the main point is to find out if this causes any issues or is overkill etc.. 如果要使用它,我将对Object.create()函数中的arg参数做一些额外的检查,但要点是要找出这是否引起任何问题或是否过大。

Yes, one very large pitfall: you're stepping on the toes of the definition ! 是的,有一个很大的陷阱:您正在踩定义的脚趾!

Object.create already takes a second parameter, an object mapping keys to property descriptors. Object.create已经有第二个参数,一个将键映射到属性描述符的对象。

This one is hard to polyfill in older environments, which is why it's still widely ignored, but when it becomes more ubiquitous, your shim will mismatch the standards pretty badly. 在较旧的环境中很难填充该填充物,这就是为什么它仍然被广泛忽略的原因,但是当它变得更加普遍时,您的垫片将严重地使标准不匹配。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM