Reputation: 2018
Question based on this discussion: Adding code to a javascript function programmatically
I read this question in hopes of finding a universal way to append code to a JS function. Unfortunately, the top answer of that question only seems to work with functions that are globally available. I need a way for this to work without a global scope. For example, 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();
If you run this code, you'll get an error saying something like: ReferenceError: Can't find variable: someFunction
. I'm not sure why this is happening with this code since I was told that this method of appending code would work in any scope, but that does not seem to be the case, at least with this code. Does anyone know a way to fix this and make the code above work?
EDIT:
Sorry, never mind. There was just a few dumb typos that I made.
Upvotes: 1
Views: 104
Reputation: 3121
The closure is surely messing up your code. Here is the shortest and simplest solution I can think of:
function SomeClass () {
this.someFunction = function() {
alert("done");
};
var cached_function = this.someFunction;
this.someFunction = function() {
alert("new code");
cached_function.apply(this, arguments);
}
}
Upvotes: 2
Reputation: 9789
Aside from the misspelling of someInstance, the issue is your closure scope and the fact that someFunction is not visible in your new self executing function. You need to pass in a reference to the containing scope's this to have access to it in your new scope:
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();
Upvotes: 3