I wanted to add a constant to the prototype of a function constructor (class) but it is coming back as undefined why?
function myClass(){
}
$(document).ready(function(){
myClass.prototype.age = 22;
window.alert(myClass.age);
});
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Because its prototypical inheritance.
The following would work:
In your example you are adding properties to the class prototype. You only see these when you instantiate an object of that class.
To achieve what you want, just rely on an expando property:
If its helpful, think of the first sample as declaring a public property on a class in C#. You can only access it when you instantiate.
The second example is like declaring a public
staticproperty on a class in C#. You don’t need to instantiate it to access it.EDIT FOR COMMENT
To access the age from within a method in the class, use this
this