【发布时间】:2012-10-28 03:41:07
【问题描述】:
假设我想创建以下 API:
var api = function(){}
api.prototype = {
constructor: api,
method: function() {
return this;
}
};
现在,这将像这样工作:
var myApi = new api();
myApi.method();
但是假设我想让 new 关键字可选,这样就可以了:
api().method();
我会疯掉的:
var api = function() {
if ( !(this instanceof api) ) {
return new api();
}
};
但我想知道,这会不会很容易被感染,或者使用这种方法有其他危险吗?我知道 f.ex jQuery 不这样做(他们将构造函数卸载到原型方法),所以我确信不这样做是有充分理由的。我只是不认识他们。
【问题讨论】:
-
您的解决方案看起来非常好,我已经看到很多地方都在使用它。例如,请参阅here。
标签: javascript constructor new-operator javascript-objects