基于此讨论的问题:Adding code to a javascript function programmatically
我阅读this question是希望找到一种通用的方法来将代码附加到JS函数中。不幸的是,这个问题的the top answer似乎只适用于全球可用的函数。我需要一种不需要全局作用域的方法。例如,https://jsfiddle.net/Ylluminarious/rc8smp1z/
function SomeClass () {
this.someFunction = function() {
alert("done");
};
this.someFunction = (function() {
var cached_function = someFunction;
return function() {
alert("new code");
cached_function.apply(this, arguments); // use .apply() to call it
};
}());
}
someInstance = new SomeClass();
someIntance.someFunction();如果你运行这段代码,你会得到一个类似于:ReferenceError: Can't find variable: someFunction的错误信息。我不确定为什么这段代码会发生这种情况,因为我被告知这种附加代码的方法可以在任何范围内工作,但情况似乎并非如此,至少对于这段代码是这样的。有没有人知道修复这个问题并让上面的代码正常工作的方法?
编辑:
对不起,不要紧。我只是犯了几个愚蠢的打字错误。
发布于 2015-04-21 00:59:48
除了someInstance的拼写错误之外,问题还在于您的闭包范围以及someFunction在新的自执行函数中不可见的事实。您需要传入对包含作用域的this的引用,才能在新作用域中访问它:
function SomeClass () {
this.someFunction = function() {
alert("done");
};
this.someFunction = (function(that) {
var cached_function = that.someFunction;
return function() {
alert("new code");
cached_function.apply(this, arguments); // use .apply() to call it
};
}(this));
}
someInstance = new SomeClass();
someInstance.someFunction();发布于 2015-04-21 01:10:10
闭包肯定会弄乱你的代码。这是我能想到的最短、最简单的解决方案:
function SomeClass () {
this.someFunction = function() {
alert("done");
};
var cached_function = this.someFunction;
this.someFunction = function() {
alert("new code");
cached_function.apply(this, arguments);
}
}https://stackoverflow.com/questions/29753865
复制相似问题