Trialcoder
Trialcoder

Reputation: 6004

use of prototype in javascript

I am learning prototype in JavaScript and this is the code I am trying -

<script>
function employee(name, age, sex) {
    this.name = name;
    this.age = age;
    this.sex = sex;
}

var trialcoder = new employee('trialcoder', 26, 'M');
//employee.prototype.salary = null;
trialcoder.salary = 19000;

document.write("salary is "+ trialcoder.salary);
</script>

My thoughts- To add another property we need to use prototype like - employee.prototype.salary = null; so on un commenting this line, I was expecting an error but it was not..let me know where I am wrong in the prototype concept.

Code Source - http://www.w3schools.com/jsref/jsref_prototype_math.asp

Upvotes: 0

Views: 160

Answers (2)

EduardoSaverin
EduardoSaverin

Reputation: 545

Your code is right and you will not receive error because using prototype your setting property salary of class employee and after creating an object of your class ur are setting the property for that specific object,if you create another object you can set its property salary too If you set property using prototype then all objects of that class will share that (salary) property .

Upvotes: 0

The Alpha
The Alpha

Reputation: 146191

Your code is correct, because when you called

var trialcoder = new employee('trialcoder', 26, 'M');

You got an object instance of employee and just like any other object you can add properties to your trialcoder object like

trialcoder.salary = 19000;

In this case, the salary property is only available to your trialcoder object and if you make another instance of employee like var another = new employee() you have no salary property in another object, but, if you do something like

function employee(name, age, sex) { //... }
employee.prototype.salary = 19000;

and then make instances like

var anEmp = new employee();
console.log(anEmp.salary); // 19000

Make another instance

var newEmp = new employee();
console.log(newEmp.salary); // 19000

if you want, you can

newEmp.salary = 10000;
console.log(anEmp.salary); // 10000

Which means, when you add a property in the prototype of a constructor (employee) then every object instance can share the same property and after making an instance from the constructor, you can change the property of an instance but this won't effect other instances. Hope it's clear enough now.

Upvotes: 5

Related Questions