给出一些像这样的javascript:
doSomething()
如何重新定义函数,以便例如i_name = my_tok(read, "/");
返回2,但不会丢失任何其他属性?
我已经为OOP找到了很多关于这类事情的答案,但我不是在这里使用“new”,只是直接调用函数。
答案 0 :(得分:2)
你可以这样做:
var doSomething = function() {
return doSomething.returnVal;
}
doSomething.returnVal = 1; // Without this, doSomething returns undefined
console.log(doSomething()); // <= 1
doSomething.returnVal = 2;
console.log(doSomething()); // <= 2
&#13;
如果你想对函数做一些更戏剧性的改变(即改变它运行的算法而不仅仅是其中的数据值),那么最好的方法可能是创建一个全新的函数并复制属性您的旧功能:
function copyProperties(source, destination) {
for (var property in source) {
destination[property] = source[property];
}
}
var doSomething = function() {
return 1;
}
doSomething.someProperty = "a";
var doSomethingElse = function() {
return 2;
}
copyProperties(doSomething, doSomethingElse);
console.log(doSomethingElse()); // <= 2
console.log(doSomethingElse.someProperty); // <= a
&#13;
答案 1 :(得分:2)
您可以将原始功能的属性分配给新功能:
原始答案:
function redefineFunction(oldFn, newFn) {
Object.assign(newFn, oldFn);
return newFn;
}
// Original function and properties
var doSomething = function() { return 1 };
doSomething.someProperty = "a";
// Redefine
doSomething = redefineFunction(doSomething, function() { return 2 });
console.log(doSomething);
console.log(doSomething());
console.log(doSomething.someProperty);
&#13;
使用Object.assign
简化而无需功能:
var doSomething = function() {
return 1
};
doSomething.someProperty = "a";
// Redefine
doSomething = Object.assign(function() {return 2}, doSomething);
console.log(doSomething);
console.log(doSomething());
console.log(doSomething.someProperty);
&#13;