我有點失落了。我知道一個事實,我需要將這個分配給另一個變量(例如:var),以使這些方法可以鏈接。在不修改修改功能的情況下,我可以使這個鏈接成爲可能? 如果你們中的任何人都能弄清楚,那麼你能向我解釋一下嗎?可連接的對象方法
function modifyFunction(f) {
console.log(f);
return function() {
var returnValue = f.apply(this, arguments);
if (returnValue == undefined) {
return this;
} else {
return returnValue;
}
};
}
function modifyMethod(o, m) {
if (o.hasOwnProperty(m)) {
console.log(o[m] instanceof Function);
if (o[m] instanceof Function) {
if (m == "add") {
modifyFunction(this.o[m]);
}
console.log(this.o[m]);
modifyFunction(o[m]);
return this;
}
} else {
return this
}
}
var o = {
num: 0,
add: function(x) {
return this.num += x;
},
sub: function(x) {
return this.num -= x;
}
};
// We can't chain object o's method because they don't return "this"
//o.add(4).sub(2); // fail - the methods aren't chainable yet!
// Make the add method chainable.
modifyMethod(o, "add");
// Now we can chain the add methods
o.add(2).add(4);
console.log(o.num); // o.num = 6
// Now make the sub method chainable
modifyMethod(o, "sub");
// Now we can chain both the sub and add methods
o.sub(1).add(3).sub(5);
console.log(o.num); // o.num = 3
只修改modifyMethod函數:) – DevBear15