我读过很多关于 JavaScript 中链式函数的内容,不知何故,我真的很困惑是否可以跨链传递参数。
我的主要目标是重新创建“类似 jQuery”的行为,在链上传递函数的第一个参数。
这是一个粗略的示例:
;(function(window) {
var test = {};
test.a = function(i){
return i+1;
};
window.test = test
})(typeof window != 'undefined' ? window : undefined);
console.log( test.a(1)) //-> should output 2
console.log( test.a(1).a()) // -> should output 3
console.log( test.a(1).a().a()) // -> should output 4
PS 我想这可以使用描述的原型(prototype)来解决 here但我真的不想搞乱原型(prototype),也不想提及使用测试对象的存储属性不能满足我的需求。
最佳答案
好吧,这非常简单 - 您需要使用流畅的界面并定义 valueOf
来允许您的对象表示为数字。您无法获得该数字,但您可以出于所有实际目的获得代表该数字的东西:
var test = {
counter: 1,
a: function(n){ this.counter += n; return this; },
valueOf: function(){ return this.counter; }
};
console.log(Number(test)); // when I look at test as a number, it returns the counter
console.log(test.a(1).a(2) + 1); // logs 5
console.log(test + test); // 8
console.log(test.a(1).a(1).a(1) + 1); // 7
就我个人而言,我更喜欢返回一个新对象以使其不可变:
function Chain(i){
this.counter = i;
}
Chain.prototype.add = function(n){
return new Chain(n + this.counter);
};
Chain.prototype.valueOf = function(){ return this.counter; };
关于Javascript 链接和传递参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30969968/