-1

I have followed this answer to create a JS constructor:

function ObjectOne(value) {
  var myVal = value;
}

function ObjectTwo(val) {
  this.val = val;
}

And i want to access that variable like this: new ObjectOne("asdf").myVal but that doesn't work (returns undefined)

jsfiddle

EDIT: IM RETARDED

There was typo in ObejctOne and ObjectTwo, (ill bury myself deep)

new version

Community
  • 1
  • 1
kajacx
  • 12,361
  • 5
  • 43
  • 70
  • possible duplicate of [Javascript: Do I need to put this.var for every variable in an object?](http://stackoverflow.com/questions/13418669/javascript-do-i-need-to-put-this-var-for-every-variable-in-an-object) – Bergi Sep 08 '13 at 21:23

1 Answers1

1

Variables declared with var in the constructor are private variables that can't be accessed from outside the constructor.

To get the value of that variable, you'll have to provide a getter method:

function ObjectOne(value) {
    var myVal = value;
    this.getMyVal () {
        return myVal;
    }
}
Joseph Silber
  • 214,931
  • 59
  • 362
  • 292