我不知道如何命名标题,抱歉。
这是一个例子,我希望能够做到这一点:
var str = 'bla bla bla';
str.do(a).thenDo(b)
//but i also want to be able to do this:
str.do(a) // which will do something different
// I have tried this but it doesn't work:
String.prototype.do = function(a) {
//here is some code to get the 'str' variable, then:
var self = {};
self.thenDo = function(b) {
var someCalculations;
return someCalculations + a + b;
}
self = function() {
//this is supposed to be the do(a) function
var moreCalculations;
return moreCalculations + a;
}
return self;
}
注意:thenDo()需要使用do()中的'a'参数,所以这样的东西 not 帮助我想要实现的目标:
String.prototype.do = function(a) {
var moreCalculations;
return moreCalculations + a;
}
String.prototype.do.thenDo = function(b) {
var someCalculations;
return someCalculations + a + b;
}
//it doesnt work, thenDo() cant get the 'a' parameter
此外,我需要这个我正在开发的库,所以任何jQuery答案都无济于事。
由于
答案 0 :(得分:2)
你说过:
str.do(a).thenDo(b) //but i also want to be able to do this: str.do(a) // which will do something different
不可能,do(a)
部分要做不同的操作,具体取决于是否使用了其返回值。例如,do(a)
和str.do(a)
的{{1}}部分无法知道它在这两种情况下的意思是做些不同的事情。它只是没有那些信息(这是一件好事™)。
你可以做到这一点:
str.do(a).thenDo(b)
请注意第一个结尾处的str.do(a)(); // Does one thing
str.do(a).thenDo(b); // Does something else
。这是触发器,让我们区分这两种情况:
()

附注:当扩展内置原型(许多人提倡反对)时,始终一定要使用(function() {
function String$do(v1) {
// This function is called if the caller uses () on the result
function immediate() {
console.log("something: ", v1);
}
// This is called if they use .thenDo() instead
immediate.thenDo = function(v2) {
console.log("something else: ", 1, v2);
};
return immediate;
}
Object.defineProperty(String.prototype, "do", {
value: String$do
});
})();
var str = "testing 1 2 3";
str.do(42)();
str.do(42).thenDo(67);
或Object.defineProperty
并使用默认值Object.defineProperties
1}}标记(或明确将其设置为enumerable
),这样您就不会创建可枚举的属性。这对命名冲突没有帮助,但它可能有助于代码天真地假设false
循环,for-in
检查等中只有默认的内置原型属性集。