假设我有一个这样的函数:
function foo(){
var myValue = 5;
var myOtherValue = 1;
return {
getValue: function(){
return [myValue, myOtherValue];
}
}
}
有没有一种方法可以在不触及原始函数的情况下以某种方式扩展/覆盖此函数,以便当我调用 getValue()
时我得到[我选择的其他值,myOtherValue]
?
如果没有,我可以在实例级别执行此操作吗?
var myFoo = new foo();
myFoo.getValue = function(){
return [0, myOtherValue]; // how to I access myOtherValue?
}
最佳答案
如果你不想修改foo,可以这样做:
function foo(){
var myValue = 5;
var myOtherValue = 1;
return {
getValue: function(){
return [myValue, myOtherValue];
}
}
}
var myFoo = new foo();
//move getValue to _getValue
myFoo._getValue = myFoo.getValue;
//do custom getValue
myFoo.getValue = function(){
return [0, myFoo._getValue()[1]];
}
关于javascript - 扩展函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22053968/