Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't this edit to a prototype work?

Tags:

javascript

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);

});
like image 442
Exitos Avatar asked Jan 20 '23 11:01

Exitos


1 Answers

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);
}
like image 107
James Wiseman Avatar answered Feb 02 '23 23:02

James Wiseman