将另一个方法应用于Object / Array

时间:2016-12-04 13:41:32

标签: javascript

如何在方法链之间调用另一种方法?

function double(base) {
  return base * 2;
}
function mapDouble(target) {
  return target.map(double);
}

var foo = [1,2,3].map(double);
console.log(foo); // => [2, 4, 6]
var bar = mapDouble([1,2,3]);
console.log(bar); // => [2, 4, 6]
var qux = [1,2,3].this.call(mapDouble);
console.log(qux);
// => Error {
//  "message": "Uncaught TypeError: Cannot read property 'call' of undefined",
//  "filename": "http://stacksnippets.net/js",
//  "lineno": 24,
//  "colno": 23
// }

我的实际代码(我想写)是

[1,2,3].map((value) => {
  return foo;
}).filter((value) => {
  return bar;
}).this.call(mapDouble);

2 个答案:

答案 0 :(得分:0)

你可以制作一个" monadic"用于创建任意函数链的工具,例如:

function begin() {
    return {
        with: function(x) {
            this.x = x;
            return this;
        },
        do: function (f) {
            this.x = f(this.x);
            return this;
        },
        end: function () {
            return this.x;
        }
    }
}

然后

function whatever(ary) {
    return ary.join('-')
}

result = begin()
    .with([1, 2, 3, 4, 5, 6, 7])
    .do(a => a.filter(x => x > 2))
    .do(a => a.map(x => x + 100))
    .do(whatever)
    .end();

答案 1 :(得分:0)

语法有问题。

function double(base) {
  return base * 2;
}
function mapDouble(target) {
  return target.map(double);
}

var foo = [1,2,3].map(double);
console.log(foo); // => [2, 4, 6]
var bar = mapDouble([1,2,3]);
console.log(bar); // => [2, 4, 6]
var qux = mapDouble.call(qux, [1,2,3]);
console.log(qux);

请参阅此Demo以了解javascript调用函数的行为

它接受的参数是你正在调用的函数的参数

基本结构就像这样

functionToCall.call(this, arg1, arg2, arg3);

希望这有帮助