繁体   English   中英

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我想这可以解决使用原型,因为它在这里描述但我真的不想搞乱原型,也没有提到使用测试对象的存储属性不能满足我的需求。

好的,这很简单 - 您需要使用流体接口并定义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; };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM