2

I have an object in Javascript like this:

var Person = {name: "John", age:37}

I would like that the name will be statically accessible every time I make a new instance of the class while the age will always be new.

So for example:

var per1 = new Person();

Person.name = "Anton";
Person.age = 11;

per1.Name //Anton
per2.Name //11

var per2 = new Person();

per1.age //Anton
per2.age //37 ????

Is there a way to make it so that it works that way?

  • 1
    Check out http://stackoverflow.com/questions/1535631/static-variables-in-javascript – Dutts Feb 19 '14 at 09:23
  • You can check this as well http://stackoverflow.com/questions/7307243/how-to-declare-a-static-variable-in-javascript – V31 Feb 19 '14 at 09:32
  • thanks guys, I could not find it by myself, maybe I was using the wrong search criteria. :P –  Feb 19 '14 at 09:39
  • http://stackoverflow.com/a/16063711/1641941 new Person would work only if Person is a function not an object literal – HMR Feb 19 '14 at 10:34

1 Answers1

2

In order to make a propery static in javascript you can use prototype:

Person.prototype.name = "Anton"

UPDATED:

You might want to use it this way:

var Person = function(age){
 this.age=age;   
}
Person.prototype.name = "Anton"
var per1 = new Person(12);
console.log(per1);
Emil Condrea
  • 9,705
  • 7
  • 33
  • 52
  • So it is up to me to use it in the right way. the field is not "locked" as static because if somewhere in the code I make the mistake of writing Person.name = "Anton"; then the field will no longer be static? do I make sense? –  Feb 19 '14 at 09:31
  • @JohnDoe check this example: http://jsfiddle.net/uc97b/ Writing Person.name = "Anton" would not affect the field in any way. – Emil Condrea Feb 19 '14 at 09:52