入门读物:
按照上述模式,我创建如下库/API
var Proto = {
constructor: function () {
this.works = true;
},
method: function () {
return this.works;
}
};
现在库用户要与我的原型(prototype)(不提供工厂函数)交互,他们必须实例化和初始化对象
// 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 <Function>
和.prototype
1和2已经提到了。
3 基本上是
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
最佳答案
目前,如果您使用一个小的 API 来帮助您构建传统的构造函数,使用看起来几乎像原型(prototype)作为类的语法,那么您可能会在您的库客户端上实现最简单的操作。 API 用法示例:
// Superclass
var Person = Class.extend({
constructor: function (name) {
this.name = name;
},
describe: function() {
return "Person called "+this.name;
}
});
// Subclass
var Worker = Person.extend({
constructor: function (name, title) {
Worker.super.constructor.call(this, name);
this.title = title;
},
describe: function () {
return Worker.super.describe.call(this)+" ("+this.title+")";
}
});
var jane = new Worker("Jane", "CTO");
实现:
- Simple JavaScript Inheritance
- 我以一种可能更容易理解的方式重新实现了 Resig 的 API:rauschma/class-js
关于javascript - 处理 API 设计和 OO 糖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7835376/