【问题标题】:Object Method Chainning对象方法链接
【发布时间】:2015-11-05 03:46:24
【问题描述】:
function modifyFunction(f) {
    return function () {
        var returnValue = f.apply(this, arguments);
        console.log(returnValue);
        if (returnValue == undefined) {
            return this;
        } else {
            return returnValue;
        }
    };
}

function modifyMethod(o, m) {
    if (o.hasOwnProperty(m)) {
        if (o[m] instanceof Function) {
            o[m] = modifyFunction(m);
        }
    }
}

var o = {
    num: 0,
    add: function (x) {
        return this.num += x;
    },
    sub: function (x) {
        return this.num -= x;
    }
};

modifyMethod(o, "add");
o.add(2).add(4);
console.log(o.num); // o.num = 6
modifyMethod(o, "sub");

o.sub(1).add(3).sub(5);
console.log(o.num); // o.num = 3

我将如何使它在“if(o[m] instanceof Function)”内部的 modifyMethod 函数中与 modifyFunction 函数在发送 o[m] 时返回的值相等?我正在努力使它成为可链接的,但我很难理解这一点。

【问题讨论】:

  • 能否请您重新表述您的问题?我不清楚你想要什么。

标签: javascript function object methods method-chaining


【解决方案1】:

o.add(2).add(4); 等于o.add(2); o.add(4); 我们可以观察到o.add(2) 返回的应该是o。所以你的modifyFunction 应该返回一个函数:

  1. 用给定的参数调用传入的函数。

  2. 返回调用者。

因此,您应该始终返回 this,而不是返回 returnValue(它是 o.num,一个数字)。

另外一点是,在你的modifyMethod 中,在你检查了o[m] 是否是一个函数之后,你应该传入那个函数,而不是m,这只是关键。所以应该是o[m] = modifyFunction(o[m]);

function modifyFunction(f) {
    return function () {
        var returnValue = f.apply(this, arguments);
        // Return the object that call this function, 
        // so it becomes chainable.
        return this;
    };
}

function modifyMethod(o, m) {
    if (o.hasOwnProperty(m)) {
        if (o[m] instanceof Function) {
            // Pass o[m], not m, m is a string.
            o[m] = modifyFunction(o[m]);
        }
    }
}

var o = {
    num: 0,
    add: function (x) {
        return this.num += x;
    },
    sub: function (x) {
        return this.num -= x;
    }
};

modifyMethod(o, "add");
o.add(2).add(4);
console.log(o.num); // o.num = 6
modifyMethod(o, "sub");

o.sub(1).add(3).sub(5);
console.log(o.num); // o.num = 3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-13
    • 2015-01-15
    • 1970-01-01
    • 2019-01-09
    相关资源
    最近更新 更多