Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I took the example from this question modified a bit: What is the point of the prototype method?

function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
this.status="single"
}
employee.prototype.salary=10000000;
var fred=new employee("Fred Flintstone","Caveman",1970);
console.log(fred.salary);
fred.salary=20000;
console.log(fred.salary)

And the output in console is this:

enter image description here

What is the difference salary is in constructor but I still can access it with fred.salary, how can I see if is in constructor from code, status is still employee property how can I tell for example if name is the one of employee or has been touch by initialization?

Why is salary in constructor, when name,jobtitle,born where "touched" by employee("Fred Flintstone","Caveman",1970); «constructor»?

share|improve this question

1 Answer 1

up vote 1 down vote accepted

By setting the prototype, you are just making an object to be shared with other instances of the same type. ie,

var liz = new employee('Elizabeth','Teacher',1980);
var jane = new employee('Jane','unknown',1981);

liz.salary is same as jane.salary, even the underlying memory will be the same.

but when you set the salary of an instance, you are not changing the salary variable in the prototype, but you are defining a new property unique for that instance. so, fred.salary = 20000 will just hide the salary attribute of the prototype.

so fred.salary will make javascript engine to look for salary in the fred instance tree, upon which it will take the direct property of that instance. while liz.salary will resolve to the property in the prototype.

I hope now the console output make some sense.

share|improve this answer
    
Now I see is not under the constructor tree is on the same branch in __proto__. –  Eduard Florinescu Sep 13 '12 at 13:33

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.