Nealbo
Nealbo

Reputation: 517

How do you access constructors variables?

I have a "class" within Javascript with a variable assigned in the constructor. I also use prototype to store variables/methods:

var MyClass = function() 
{ 
    this.age = 100;
};

MyClass.prototype.name = "John";
MyClass.prototype.getAge = function() { return this.age};

alert(MyClass.prototype.name); //Alerts John
alert(MyClass.age); //undefined as expected
alert(MyClass.prototype.getAge()); //undefined??

So from what I can tell, there is no way I can access the constructor variables that are stored within MyClass unless I create an object from the Class:

var theClass = new MyClass();
alert(theClass.age);
alert(theClass.getAge());​

Both alerts will return the age correctly.

So to reiterate, can I access the constructor variables directly from the MyClass without needing to create a variable?

Upvotes: 0

Views: 244

Answers (2)

Quentin
Quentin

Reputation: 943207

So from what I can tell, there is no way I can access the constructor variables that are stored within MyClass unless I create an object from the Class

Correct. They are assigned in the function body. They won't exist until the function is executed.

So to reiterate, can I access the constructor variables directly from the MyClass without needing to create a variable?

No.

Upvotes: 2

Ernest Friedman-Hill
Ernest Friedman-Hill

Reputation: 81684

No. The variable age in your example is created when the constructor function runs; therefore it's not going to be available until you run the function.

Upvotes: 2

Related Questions