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);
});
Because its prototypical inheritance.
The following would work:
myClass.prototype.age = 22;
var myobj = new myClass();
window.alert(myobj.age);
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:
myClass.age = 22;
window.alert(myClass.age);
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 static
property 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
myClass.prototype.GetAge = function(){
alert(this.age);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With