Reputation: 28107
Is it possible to do something like this in Javascript:
var myFunction = function() {
return true;
};
var anotherFunction = function () {
return false;
};
$(function () {
this.myFunction = anotherFunction;
myFunction(); // to return false
});
My intuition says yes, but it doesn't work. How can I achieve this functionality?
Upvotes: 1
Views: 63
Reputation: 12390
Works for me jsFiddle
var myFunction = function () {
return true;
};
var anotherFunction = function () {
return false;
};
$(function () {
myFunction = anotherFunction; //remove this. your function was attach to a variable so by reassigning that variable with "anotherFunction" you will get the desired result.
$('#result').html(""+myFunction());
});
Upvotes: 1
Reputation: 27823
You can override any variable inside the outer scope with another variable with the same name:
var myFunction = function() {
return true;
};
var anotherFunction = function () {
return false;
};
$(function () {
var myFunction = anotherFunction; // override the myFunction name inside this scope
myFunction(); // returns false
});
myFunction(); // returns true
You can read more about scope here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope
Upvotes: 2
Reputation: 23250
It does work, you have just made a typo (missed off the this
) that is causing the old function to be called;
$(function () {
this.myFunction = anotherFunction;
this.myFunction(); // to return false
});
or
$(function () {
myFunction = anotherFunction;
myFunction(); // to return false
});
In the context where you are overiding, this.myFunction
and myFunction
refer to different things.
Here is your fixed fiddle: http://jsfiddle.net/ExfP6/3/
Upvotes: 2