Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I redefine a JavaScript function from within another function?

I want to pass a function reference "go" into another function "redefineFunction", and redefine "go" inside of "redefineFunction". According to Johnathan Snook, functions are passed by reference, so I don't understand why go() does not get redefined when I pass it into redefineFunction(). Is there something that I am missing?

// redefineFunction() will take a function reference and
// reassign it to a new function
function redefineFunction(fn) {
    fn = function(x) { return x * 3; };
}

// initial version of go()
function go(x) {
    return x;            
}

go(5); // returns 5

// redefine go()
go = function(x) {
     return x * 2;        
}

go(5); // returns 10

// redefine go() using redefineFunction()
redefineFunction(go);

go(5); // still returns 10, I want it to return 15

​ Or see my fiddle http://jsfiddle.net/q9Kft/

like image 827
Walter Stabosz Avatar asked Dec 20 '22 22:12

Walter Stabosz


1 Answers

Pedants will tell you that JavaScript is pure pass-by-value, but I think that only clouds the issue since the value passed (when passing objects) is a reference to that object. Thus, when you modify an object's properties, you're modifying the original object, but if you replace the variable altogether, you're essentially giving up your reference to the original object.

If you're trying to redefine a function in the global scope: (which is a bad thing; you generally shouldn't have global functions)

function redefineFunction(fn) {
    window[fn] = function() { ... };
}

redefineFunction('go');

Otherwise, you'll have to return the new function and assign on the calling side.

function makeNewFunction() {
    return function() { ... };
}

go = makeNewFunction();
like image 140
josh3736 Avatar answered Apr 19 '23 23:04

josh3736