Javascript: re-assigning a function using another function

Let's say I have two functions:

function fnChanger(fn) {
    fn = function() { sys.print('Changed!'); }
}
function foo() {
    sys.print('Unchanged');
}

Now, if I call foo(), I see Unchanged, as expected. However, if I call first fnChanger, I still see Unchanged:

fnChanger(foo);
foo(); //Unchanged

Now I assume that this is because it is foonot passed in fnChangerby reference, but I could be wrong.

Why fnChangerdoes not change footo print Changed!?
Also, how can I get fnChangerto change foowithout too much messy syntax?

PS: I use node.js to test all of this, so where does it come from sys.print.

+5
2

fn , foo .

, , " ". , fn.

JavaScript.

fnChanger , foo fn :

                ---------------------------------------------
    foo ----->  |function foo { sys.print('Un changed!'); } |
                ---------------------------------------------
                   ^
                   |
    fn -------------

fn :

                ---------------------------------------------
    foo ----->  | function foo { sys.print('Unchanged!'); } |
                ---------------------------------------------

                ---------------------------------------
    fn ------>  | function { sys.print('Changed!'); } |
                ---------------------------------------

?

, , foo , - :

function fnChanger(obj, name) {
    obj[name] = function() { sys.print('Changed!'); };
}

function foo() {
    sys.print('Unchanged');
}

fnChanger(this, 'foo');
foo(); // Changed!

, fnChanger , , , Global, .

fnChanger(this, 'foo'); , this ( ) , GlobalObject.foo.

, , " " ( ) - , ( , ), , eval.

:

+5

@CMS, - . :

var fnChanger = function() {
  return function() {
      alert('changed!');
  }
}

var foo = function() {
  alert('Unchanged');
}

foo = fnChanger();
foo();

+2

All Articles