Reputation: 10745
Why does this
alert as undefined
in the code below?
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
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