所以我正在构建一些可链接的函数来执行简单的类型检查。目前,我必须这样调用我的函数:
Proceed().if('someString').is.a('string');
但是我真正想要的是我的 API 看起来像这样:
proceed.if('someString').is.a('string');
请注意,在第二个代码示例中,第一个函数调用中缺少左括号和右括号。
正如您从下面的代码中看到的,我已经弄清楚如何让 is
和 a
工作,但我似乎找不到从 Proceed()
函数中删除括号的方法。
这是有效的代码示例:
function Proceed() {
if (!(this instanceof Proceed)) {
return new Proceed();
}
this.target = "";
}
Proceed.prototype.if = function (target) {
this.target = target;
return this;
}
Proceed.prototype.a = function (type) {
console.log(this.target + ' === ' +type, typeof this.target === type);
};
Object.defineProperty(Proceed.prototype, 'is', {
get: function () {
return this;
}
});
Proceed().if('someString').is.a('string'); // true
Proceed().if('someString').is.a('function'); // false
// Everything Above this line Works!
现在,我尝试从 Proceed()
中删除括号,如下所示:
Object.defineProperty(Proceed.prototype, 'proceed', {
set: function(){},
get: function(){
return Proceed(this);
},
configurable: true
});
proceed.if('someString').is.a('string'); // ReferenceError
proceed.if('someString').is.a('function'); // ReferenceError
我从这里得到的错误是这样的:
Uncaught ReferenceError: proceed is not defined
如果我用 Object.prototype
替换 Proceed.prototype
,那么我可以让它工作,但这意味着我扩展了一个 native 对象,这可能会出现问题。
那么有谁知道我可以在不危险地扩展 native 对象的情况下完成此任务的方法吗?我在这里做错了什么?
<强> Here is a jsFiddle with the above code samples .
感谢任何帮助。
更新 #1 此代码被设计为节点模块,因此不会对浏览器的 window
对象进行任何访问。
最佳答案
您需要从实例值变量开始:
var proceed = new Proceed();
为了使其可链接,您应该从方法中返回新实例,而不是改变“静态”proceed
对象:
function Proceed(target) {
this.target = arguments.length ? target : "";
}
Proceed.prototype.if = function (target) {
return new Proceed(target);
}
或者一般来说,您需要使 proceed.if
成为一个返回 Proceed
实例的工厂,无论 proceed
是否已经是一个或只是一个一个普通的物体。
关于javascript - API:使构造函数在 JavaScript 中无需括号即可链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35506874/