0

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?

3
  • why would you avoid to use a variable? Commented May 24, 2012 at 13:00
  • @Nealbo, You need to use like as static properties? Commented May 24, 2012 at 13:03
  • Regarding alert(MyClass.prototype.getAge()); //undefined??: It would try to access MyClass.prototype.age which does not exist. Inside the constructor this refers to an empty object with inherits from MyClass.prototype, so age will never be assigned to MyClass.prototype. Commented May 24, 2012 at 13:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.