Mike Rifgin
Mike Rifgin

Reputation: 10745

No access to this in prototype

Why does this alert as undefined in the code below?

http://jsfiddle.net/7kwXd/6/

var testObj = {};

testObj.aMethod = function() {
    this.testVar = "thing"
    alert(this.anObject.dimension1);
    alert(this.anObject.dimension2);
};

testObj.aMethod.prototype.anObject = {
   dimension1 : this.testVar,
   dimension2 : "thing2"
};

var testing = new testObj.aMethod();

Upvotes: 1

Views: 40

Answers (1)

darthmaim
darthmaim

Reputation: 5148

You are creating an object ({dimension1: this.testVar, dimension2: "thing2"}) without any object context. What is this supposed to be at that time? After that, you are assigning it to testObj.aMethod.prototype.anObject.

You can use code like this to achieve what you want:

var testObj = {};

testObj.aMethod = function() {
    this.testVar = "thing"
    alert(this.anObject.dimension1);
    alert(this.anObject.dimension2);
};

testObj.aMethod.prototype.getAnObject = function() {
   return {
       dimension1 : this.testVar,
       dimension2 : "thing2"
   };
};

var testing = new testObj.aMethod();

And then access that object with testing.getAnObject().dimension1.

Upvotes: 2

Related Questions