Javascript 链接和传递参数
Javascript chaining and passing arguments
我在 JavaScript 中阅读了很多关于链式函数的内容,不知何故我真的很困惑是否可以跨链传递参数。
我的主要目标是重新创建 "jQuery like" 在链上传递函数第一个参数的行为。
这是一个粗略的例子:
;(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 我想这可以使用描述的原型来解决 here 但我真的不想弄乱原型,也不想提及使用测试对象的存储属性不能满足我的需求。
好的,这很简单 - 您需要使用流畅的界面并定义 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 中阅读了很多关于链式函数的内容,不知何故我真的很困惑是否可以跨链传递参数。
我的主要目标是重新创建 "jQuery like" 在链上传递函数第一个参数的行为。
这是一个粗略的例子:
;(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 我想这可以使用描述的原型来解决 here 但我真的不想弄乱原型,也不想提及使用测试对象的存储属性不能满足我的需求。
好的,这很简单 - 您需要使用流畅的界面并定义 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; };