简介阅读:
按照上述模式,我创建如下的库/API:
var Proto = {
constructor: function () {
this.works = true;
},
method: function () {
return this.works;
}
};
现在,对于需要与我的原型进行交互的库用户(原型不提供工厂函数),他们必须实例化并初始化对象。
// instantiate
var p = Object.create(Proto);
// initialize
p.constructor();
这是一种不友好且啰嗦的方式,强制用户实例化和初始化我的对象。
个人而言,因为我在所有应用程序中使用
pd
,所以我有以下简化语法糖。// instantiate or initialize
var p = Proto.new();
// or without bolting onto Object.prototype
var p = pd.new(Proto);
然而,我认为强制用户使用pd并不好,因此我不确定使我的库可用的最佳方法是什么。
- 人们创建Proto的新实例并自己调用.constructor
- 强制人们使用pd
- 提供.create样式的工厂函数
- 放弃并使用new 和.prototype
已经提到了1和2。
3基本上就是提供.create样式的工厂函数。
Proto.create = pd.new.bind(pd, Proto);
4会让我感到悲伤,但是遵循已知的标准做事方式可以提高可用性。
通常,当使用非标准OO模式时,最容易让人们在其应用程序中使用我的库的机制是什么?
我目前的倾向是
// here is my Prototype
Proto;
// here is how you instantiate a new instance
var p = Object.create(Proto);
// here is how you initialize it
// yes instantiation and initialization are seperate and should be.
p.constructor();
// Want sugar, use pd.new