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?

4
  • 1
    Check out stackoverflow.com/questions/1535631/… Commented Feb 19, 2014 at 9:23
  • You can check this as well stackoverflow.com/questions/7307243/… Commented Feb 19, 2014 at 9:32
  • thanks guys, I could not find it by myself, maybe I was using the wrong search criteria. :P Commented Feb 19, 2014 at 9:39
  • stackoverflow.com/a/16063711/1641941 new Person would work only if Person is a function not an object literal Commented Feb 19, 2014 at 10:34

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

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?
@JohnDoe check this example: jsfiddle.net/uc97b Writing Person.name = "Anton" would not affect the field in any way.