簡體   English   中英

在javascript中擴展Object.create()

[英]extending Object.create() in javascript

我正在擴展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參數做一些額外的檢查,但要點是要找出這是否引起任何問題或是否過大。

是的,有一個很大的陷阱:您正在踩定義的腳趾!

Object.create已經有第二個參數,一個將鍵映射到屬性描述符的對象。

在較舊的環境中很難填充該填充物,這就是為什么它仍然被廣泛忽略的原因,但是當它變得更加普遍時,您的墊片將嚴重地使標准不匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM