Friday, March 27, 2015

3/27/15 - Strange Javascript

Finn had posted this code snippet on his blog a couple of days ago, and Kevin wanted to talk to me about it If you actually run this in a terminal, javascript throws an error: Uncaught TypeError: Cannot read property 'otherVariable' of undefined. This is attempting to treat a javascript function directly as an object, which isn't allowed. If you do console.log(variables) it prints:
function variables(){
  this.number     = 1;
  this.stringVariable = "test";
  this.otherVariable = 2.0;
}
and console.log(variables()); [notice the () after variables] prints:
undefined
In order for this to work as intended, you need to get an object instance from this class:
var variablesObj = new variables
Then console.log(variablesObj) ->
variables {number: 1, stringVariable: "test", otherVariable: 2}

So now we can do variablesObj.number, variablesObj.stringVariable, etc.
It's also good to note that if you set variablesObj.number = 2, the field will update. The initial code of setting number to 1 is only run once, when the object is first instantiated with the new keyword.

1 comment:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain

    and

    http://www.crockford.com/javascript/inheritance.html

    ReplyDelete