Kyle Simpsons 的 OLOO 在 Object.create 之后添加多个属性

Kyle Simpsons's OLOO adding Multiple properties after Object.create

我最近才了解到 Kyle Simpson 创造的 "OLOO" 委托模型(而不是继承),他使用类似于下面的代码片段创建对象并委托属性和函数:

var Foo = {
    init: function(who) {
        this.me = who;
    },
    identify: function() {
        return "I am " + this.me;
    }
};

var Bar = Object.create(Foo);

Bar.speak = function() {
    alert("Hello, " + this.identify() + ".");
};

var b1 = Object.create(Bar);
b1.init("b1");
var b2 = Object.create(Bar);
b2.init("b2");

b1.speak(); // alerts: "Hello, I am b1."
b2.speak(); // alerts: "Hello, I am b2."

在这里,Bar 将所有对 "init" 和 "identify" 的调用委托给 "Foo" 对象,但是在创建 Bar 之后我们必须逐行添加任何Bar 的其他属性通过:

Bar.someAdditionalFunc = function(){ /* Do something else for Bar */ };
Bar.someAdditionalProp = { prop: 'Value' };

我的问题是:有没有什么方法可以在不使用点符号的情况下为(可能的)大条形预定义(或 post-定义)所有这些属性(Bar.PropertyName = ...) 对于每个新 属性?

例如,我想做这样的事情:

var BarTemp = {
    someAdditionalFunc: function(){ /* Do something else for Bar */ },
    someAdditionProp: { prop: 'Value' }
};

var Bar = Object.create(Foo, BarTemp);

这正确地创建了 Bar 对象,其中创建了 someAdditionFunc 和 someAdditionalProp 属性,但它们都设置为 'undefined'。我想这是正确的行为,但我想知道我是坚持使用 jQuery.extend() 还是像这样创建另一个子对象:

var subObject = {
    someAdditionalFunc: function() {},
    someAdditionalProp: { prop: 'value' }
    // ... all other properties we want to add
}

var Bar = Object.create(Foo);
Bar.otherStuff = subObject; 
// Now I always have to reference those properties by:
//    Bar.otherStuff.someAdditionalFunc
// instead of:
//    Bar.someAdditionalFunc

或者有更简单的方法 implement/think 吗?

有几个选项可以减少步骤,但这实际上取决于您的浏览器支持要求。第二个选项也不是特别"simple",也不是!

Object.setPrototypeOf() (ES6)

因为这是在 ES6 中,所以只有当您使用已知 JavaScript 引擎的服务器端代码时,它才真正有用,否则您将不得不填充。请参阅 compatability chart here.

var foo = {
  bar: function() { console.log("bar"); }
}

var baz = {
  someProp: 'a',
  someFunc: function () { console.log("dork"); }
}


Object.setPrototypeOf( baz, foo );
baz.someFunc() // "dork"
baz.bar()      // "bar"

Object.create( proto , propertiesObject ) (ES5)

这得到了更广泛的支持,但可能仍会导致您使用旧版本的 IE 出现问题。

基本上,您的问题差不多就解决了,只是您需要使用 property descriptors 而不仅仅是属性和值的散列:

var foo = {
  bar: function() { console.log("bar"); }
}

var b = Object.create( foo, {
  baz: {
    value: function() { console.log("baz") },
    writable: true,      // default: false
    enumerable: true,   // default: false
    configurable: true,  // default: false
  },
  defProps: {
    value: function() { console.log("default"); }
  }
});

b.bar();      // bar
b.baz();      // baz
b.defProps(); // default

for(var prop in b){
 console.log(prop); // baz, bar
}

delete b.defProps;   //typeError
b.defProps = "test"; //typeError

这个问题,如上面的 defProps 对象所示,是对象 属性 描述符的默认值几乎总是不是你想要的,所以它最终变得非常冗长甚至更乏味。