处理API设计和OO糖

Ray*_*nos 6 javascript api

介绍性阅读:

按照上面描述的模式,我创建库/ API如下

var Proto = {
  constructor: function () {
    this.works = true;
  },
  method: function () {
    return this.works;
  }
};
Run Code Online (Sandbox Code Playgroud)

现在,对于库用户与我的原型(不提供工厂函数)进行交互,他们必须实例化并初始化对象

// instantiate
var p = Object.create(Proto);
// initialize
p.constructor();
Run Code Online (Sandbox Code Playgroud)

这是一种迫使用户实例化和初始化对象的不友好且冗长的方式.

个人,因为我pd在我的所有应用程序中使用我有以下糖

// instantiate or initialize
var p = Proto.new();
// or without bolting onto Object.prototype
var p = pd.new(Proto);
Run Code Online (Sandbox Code Playgroud)

但是我认为强迫pd到用户是不友好的,所以我不确定什么是使我的库可用的最佳方法.

  1. 人们创造新的实例Proto并称呼.constructor自己
  2. 强迫人们使用 pd
  3. 提供.create样式工厂功能
  4. 放弃并使用new <Function>.prototype

已经提到过1和2.

3基本上是

Proto.create = pd.new.bind(pd, Proto);
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

Axe*_*yer 2

目前,如果您使用一个小型 API 来帮助您构建传统的构造函数,使用看起来几乎像原型即类的语法,那么您可能会在库客户端上变得最简单。API 使用示例:

\n\n
// Superclass\nvar Person = Class.extend({\n    constructor: function (name) {\n        this.name = name;\n    },\n    describe: function() {\n        return "Person called "+this.name;\n    }\n});\n\n// Subclass\nvar Worker = Person.extend({\n    constructor: function (name, title) {\n        Worker.super.constructor.call(this, name);\n        this.title = title;\n    },\n    describe: function () {\n        return Worker.super.describe.call(this)+" ("+this.title+")";\n    }\n});\nvar jane = new Worker("Jane", "CTO");\n
Run Code Online (Sandbox Code Playgroud)\n\n

实施:

\n\n\n