Why doesn't this edit to a prototype work?
-
28-10-2019 - |
Question
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);
});
Solution
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);
}
OTHER TIPS
Using something.bar
only works when something
is an instance of a class.
My pattern for creating "class static" variables looks like this:
var MyClass = function() {
if (typeof this.constructor.static === 'undefined') {
// create (and initialise) default static variables
this.constructor.static = { age: 22 };
}
// create a local alias
var static = this.constructor.static;
// now you can use "static.variableName" as a class static
alert(static.age);
}