Understanding the Prototype Method in JavaScript

javascriptprototypingtechnique

I am reading through Javascript: The Good Parts, and struggled to get my head around the section on prototypes.

After a little google, I came to the conclusion that it is to add properties to objects after the objects declaration.

Using this script gleamed from w3schools, I noticed that removing the line adding the prototype property had no effect. So what is the point?


//Prototyping

function employee(name,jobtitle,born)
{
this.name=name;
this.jobtitle=jobtitle;
this.born=born;
}

var fred=new employee("Fred Flintstone","Caveman",1970);
employee.prototype.salary=null; //  <---  try removing this line
fred.salary=20000;

document.write(fred.salary);

Best Answer

That's not how the prototype works. The prototype is used in the prototype chain.

Whenever you try to get a property on an object it will check the object for that property name. If it does not exist it will look in the prototype.

Example:

var o = {
  "foo": "bar",
  "method": function() { ... }
};

var o2 = Object.create(o);
var o3 = Object.create(o);

console.log(o2.hasOwnProperty("foo")); // false
console.log(o2.foo); // "bar"
console.log(o2.__proto__ === o); // true
o.baz = "foobar";
console.log(o2.baz); // "foobar"

So the point of the prototype is simply code re-use and inheritance.

Related Topic