Friday, 14 September 2012

Javascript - Objects by ref

If any language should have been name after a snake, Javascript should have. It's a slippery little thing I tell you. It slithers and slides and wraps around you. And you have to work like a snake charmer to coax it out of its basket and make it play nicely without biting you.

Take, for example the simple idea of passing a variable by ref or by val. Javascript's snakey little implementation means that if you are passing a variable then you'll never pass it by ref. However if you are passing an object, then, hey presto, by ref it is. Bear witness:

var globalVar;
      var anObj = function() {
        this.value = "default value";
      }

      function changeValue(arg){
        arg.value = "Changed by function";
      }

      function changeUp(arg) {
        arg = "Changed";
      }


      globalVar = "global";
      console.log(globalVar);
      changeUp(globalVar);
      console.log(globalVar);

      var myObj = new anObj();
      console.log(myObj.value);
      changeValue(myObj);
      console.log(myObj.value);

Yep, slap that into some html and run it with your Chrome developer console up and about and you will see something like this:

global
global
default value
Changed by function

Yes sir! that Javascript. She's a tricky little snake of a language. Nothing at all like Python. Nothing at all like Asp. Nope, it's in a league of its own.

No comments:

Post a Comment