Rectangle 27 1

How does JavaScript .prototype work?


//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);
Object {Person: function, getName: function, name: "George"}
Person
Person("George");
getName();//would print the "George" in the console
Person.apply(newObject, ["George"]);
Person.call(newObject, "George");
Person.call(person, "George");
console.log(Object.prototype.__proto__===null);//true
console.log(person.__proto__===propertiesObject); //true
for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}
function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");
function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };
getName
my_person_prototype
new
new FunctionName()
newObject.getName();
person
person.Person = Person;
person.getName = getName;
person.Person("George");
person.getName();// -->"George"
person.__proto__ = {
    Person: Person,
    getName: getName
};
person.__proto__.Person = Person;
person.__proto__.getName = getName;
this
var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
var newObject = {};
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}
var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

do the same exact thing without using prototype and new keyword

+1 for the illustration at the end of your "book" :)

-The easiest way to do this is modifying the empty person object, like:

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So in this step functions, objects and this keyword, are all we have.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

The call() method calls a function with a given this value and arguments provided individually.

There are some crucial points that we have to consider before going through the prototype concept.

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

and

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

and that's how inheritance works in JavaScript.

as you see using any of these two way this would exactly point to the person object.

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

now the end result before simulating the other steps: Object {name: "George"}

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

this way we can call them like:

this way which is my favorite, we can easily call our functions like:

we can do this with our sample like:

we have my_person_prototype here similar to the prototype object.

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

Note
Rectangle 27 1

How does JavaScript .prototype work?


//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);
Object {Person: function, getName: function, name: "George"}
Person
Person("George");
getName();//would print the "George" in the console
Person.apply(newObject, ["George"]);
Person.call(newObject, "George");
Person.call(person, "George");
console.log(Object.prototype.__proto__===null);//true
console.log(person.__proto__===propertiesObject); //true
for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}
function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");
function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };
getName
my_person_prototype
new
new FunctionName()
newObject.getName();
person
person.Person = Person;
person.getName = getName;
person.Person("George");
person.getName();// -->"George"
person.__proto__ = {
    Person: Person,
    getName: getName
};
person.__proto__.Person = Person;
person.__proto__.getName = getName;
this
var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
var newObject = {};
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}
var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

do the same exact thing without using prototype and new keyword

+1 for the illustration at the end of your "book" :)

-The easiest way to do this is modifying the empty person object, like:

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So in this step functions, objects and this keyword, are all we have.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

The call() method calls a function with a given this value and arguments provided individually.

There are some crucial points that we have to consider before going through the prototype concept.

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

and

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

and that's how inheritance works in JavaScript.

as you see using any of these two way this would exactly point to the person object.

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

now the end result before simulating the other steps: Object {name: "George"}

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

this way we can call them like:

this way which is my favorite, we can easily call our functions like:

we can do this with our sample like:

we have my_person_prototype here similar to the prototype object.

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

Note
Rectangle 27 1

How does JavaScript .prototype work?


//apply is more useful when params count is not fixed
Person.apply(person, ["George"]);

getName.call(person);   
getName.apply(person);
Object {Person: function, getName: function, name: "George"}
Person
Person("George");
getName();//would print the "George" in the console
Person.apply(newObject, ["George"]);
Person.call(newObject, "George");
Person.call(person, "George");
console.log(Object.prototype.__proto__===null);//true
console.log(person.__proto__===propertiesObject); //true
for(var key in my_person_prototype){
    newObject[key] = my_person_prototype[key];
}
function Person(name){
    this.name = name;
}
Person.prototype.getName = function(){
    console.log(this.name);
}
var person = new Person("George");
function Person(name){  this.name = name;  }
my_person_prototype = { getName: function(){ console.log(this.name); } };
getName
my_person_prototype
new
new FunctionName()
newObject.getName();
person
person.Person = Person;
person.getName = getName;
person.Person("George");
person.getName();// -->"George"
person.__proto__ = {
    Person: Person,
    getName: getName
};
person.__proto__.Person = Person;
person.__proto__.getName = getName;
this
var newObject = Object.create(my_person_prototype);
//here you can check out the __proto__ attribute
console.log(newObject.__proto__ === my_person_prototype); //true
//and also check if you have access to your desired properties
console.log(typeof newObject.getName);//"function"
var newObject = {};
var person = {};
function Person(name){  this.name = name;  }

function getName(){
    console.log(this.name);
}
var propertiesObject = {
    Person: Person,
    getName: getName
};
var person = Object.create(propertiesObject);

do the same exact thing without using prototype and new keyword

+1 for the illustration at the end of your "book" :)

-The easiest way to do this is modifying the empty person object, like:

-The other way to attach a property to an object is using the prototype of that object that can be find in any JavaScript object with the name of __proto__, and I have tried to explain it a bit on the summary part. So we could get the similar result by doing:

@Bergi: thanks for pointing out, I'd be appreciated if you let me know if that's ok now.

@P.M: Thanks for your feedback. I've tried to make it as simple as possible but I think you are right it has still some vague points. So I will try to modify it and also be more descriptive. :)

Basically, when you use the new keyword on a function, you are calling on that and that function serves as a constructor, so when you say:

But the tricky point here is you have access to all the properties defined in __proto__ on the first level of the person object(read the summary part for more detail).

But this way what we actually are doing is modifying the Object.prototype, because whenever we create a JavaScript object using literals ({ ... }), it gets created based on Object.prototype, which means it gets attached to the newly created object as an attribute named __proto__ , so if we change it, as we have done on our previous code snippet, all the JavaScript objects would get changed, not a good practice. So what could be the better practice now:

Can you please make it simple? You are right on all points, but students who read this explanation may be really confused for the first time. pick up any simpler example, and let the code explain itself or add a bunch of comments to clarify what you mean.

In other words, when you have a prototype property on a function and you call a new on that, after JavaScript finishes looking at that newly created object for properties, it will go look at the function's .prototype and also it is possible that this object has its own internal prototype. and so on.

It is not the way that JavaScript actually attaches the properties that are defined in the prototype. The actual way is related to the prototype chain concept.

JavaScript internally makes an object, an empty hash and then it gives that object to the constructor, then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created and then it gives you that object of course if you haven't used the return statement in your function or if you've put a return undefined; at the end of your function body.

So in this step functions, objects and this keyword, are all we have.

So when JavaScript goes to look up a property on an object, the first thing it does, is it looks it up on that object. And then there is a secret property [[prototype]] which we usually have it like __proto__ and that property is what JavaScript looks at next. And when it looks through the __proto__, as far as it is again another JavaScript object, it has its own __proto__ attribute, it goes up and up until it gets to the point where the next __proto__ is null. The point is the only object in JavaScript that its __proto__ attribute is null is Object.prototype object:

The apply() method calls a function with a given this value and arguments provided as an array (or an array-like object).

The call() method calls a function with a given this value and arguments provided individually.

There are some crucial points that we have to consider before going through the prototype concept.

This is a very simple prototype based object model that would be considered as a sample during the explanation, with no comment yet:

To take the first step we have to figure out, how JavaScript functions actually work , as a class like function using this keyword in it or just as a regular function with its arguments, what it does and what it returns.

a) Please don't explain prototypes by copying properties b) Setting the internal [[prototype]] happens before the constructor function is applied on the instance, please change that order c) jQuery is totally offtopic in this question

and

and now other objects are in peace, but it still doesn't seem to be a good practice. So we have still one more solutions, but to use this solution we should get back to that line of code where person object got created (var person = {};) then change it like:

and now without using new keyword how we could use these functions. So JavaScript has 3 different ways to do that:

and that's how inheritance works in JavaScript.

as you see using any of these two way this would exactly point to the person object.

in this case, this would be the current context object, which is usually is the global window object in the browser or GLOBAL in Node.js. It means we would have, window.name in browser or GLOBAL.name in Node.js, with "George" as its value.

in this part I'm gonna be trying to take all the steps which JavaScript takes, without using the new keyword and prototype, when you use new keyword. so when we do new Person("George"), Person function serves as a constructor, These are what JavaScript does, one by one:

now the end result before simulating the other steps: Object {name: "George"}

then the constructor can do whatever it wants, because this inside of that constructor is the object that was just created.

these 3 methods are the important initial steps to figure out the .prototype functionality.

this is the second step to understand the .prototype functionality.this is what I use to simulate the process:

this way we can call them like:

this way which is my favorite, we can easily call our functions like:

we can do this with our sample like:

we have my_person_prototype here similar to the prototype object.

what it does is creating a new JavaScript Object and attach the propertiesObject to the __proto__ attribute. So to make sure you can do:

Note
Rectangle 27 1

How does JavaScript .prototype work?


//Create a new object of type Customer by defining its constructor. It's not 
//related to Person for now.
var Customer = function(name) {
    this.name = name;
};

//Now I link the objects and to do so, we link the prototype of Customer to 
//a new instance of Person. The prototype is the base that will be used to 
//construct all new instances and also, will modify dynamically all already 
//constructed objects because in JavaScript objects retain a pointer to the 
//prototype
Customer.prototype = new Person();     

//Now I can call the methods of Person on the Customer, let's try, first 
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();

//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
    return this.amountDue;
};

//Let's try:       
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
//Define a functional object to hold persons in JavaScript
var Person = function(name) {
  this.name = name;
};

//Add dynamically to the already defined object a new getter
Person.prototype.getName = function() {
  return this.name;
};

//Create a new object of type Person
var john = new Person("John");

//Try the getter
alert(john.getName());

//If now I modify person, also John gets the updates
Person.prototype.sayMyName = function() {
  alert('Hello, my name is ' + this.getName());
};

//Call the new method on john
john.sayMyName();
//The following statement generates an error.
john.setAmountDue(1000);
Customer.prototype = Object.create(Person.prototype)
Customer.prototype = new Person();
var Person = function (name) {
    this.name = name;
};
Person.prototype.getName = function () {
    return this.name;
};
var john = new Person("John");
alert(john.getName());
Person.prototype.sayMyName = function () {
    alert('Hello, my name is ' + this.getName());
};
john.sayMyName();
var Customer = function (name) {
    this.name = name;
};
Customer.prototype = new Person();

var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
Customer.prototype.setAmountDue = function (amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function () {
    return this.amountDue;
};
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());

@stivlo This is a great answer as well! Thanks for contributing. I learned a lot both from the accepted answer and yours! :)

As far as I understand var Person = function (name) {...}; is defining a constructor function capable of building Person Objects. So there is no Object yet, only the anonymous constructor function is assigned to Person. This is a very good explanation: helephant.com/2008/08/how-javascript-objects-work

But why? The value is still an object? isn't the point here that objects and functions should be indistinguishable? besides the fact that you cannot invoke on an object.

I notice that this answer also doesn't mention that by using "new Person()" as the prototype, you are actually setting the "name" instance property of "Person" to be a static property of "Customer" (so all Customer instances will have the same property). While it's a good basic example, DON'T DO THAT. :) Create a new anonymous function to act as a "bridge" by setting it's prototype to "Person.prototype", then create an instance from it and set "Customer.prototype" to that anonymous instance instead.

I think the answers on stackoverflow are not only interesting to the original poster, but also to a big community of other people lurking or coming from searches. And I've been one of them and I had benefit from old posts. I think I could contribute to the other answers adding some code examples. About your question: if you leave out the new, it doesn't work. when I call myCustomer.sayMyName() it returns "myCustomer.sayMyName is not a function". The easiest way is experiment with firebug and see what happens.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.

In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

Until now I've been extending the base object, now I create another object and then inheriting from Person.

WARNING: This answer neglects the fact that the parent class constructor is not called on a per instance basis. The only reason it works is because he did the exact same thing (setting the name) in both the child and parent constructor. For a more in depth explanation on common mistakes made when attempting inheritance in JavaScript (and a final solution), please see: this stack overflow post

While as said I can't call setAmountDue(), getAmountDue() on a Person.

Note
Rectangle 27 1

How does JavaScript .prototype work?


//Create a new object of type Customer by defining its constructor. It's not 
//related to Person for now.
var Customer = function(name) {
    this.name = name;
};

//Now I link the objects and to do so, we link the prototype of Customer to 
//a new instance of Person. The prototype is the base that will be used to 
//construct all new instances and also, will modify dynamically all already 
//constructed objects because in JavaScript objects retain a pointer to the 
//prototype
Customer.prototype = new Person();     

//Now I can call the methods of Person on the Customer, let's try, first 
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();

//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
    return this.amountDue;
};

//Let's try:       
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
//Define a functional object to hold persons in JavaScript
var Person = function(name) {
  this.name = name;
};

//Add dynamically to the already defined object a new getter
Person.prototype.getName = function() {
  return this.name;
};

//Create a new object of type Person
var john = new Person("John");

//Try the getter
alert(john.getName());

//If now I modify person, also John gets the updates
Person.prototype.sayMyName = function() {
  alert('Hello, my name is ' + this.getName());
};

//Call the new method on john
john.sayMyName();
//The following statement generates an error.
john.setAmountDue(1000);
Customer.prototype = Object.create(Person.prototype)
Customer.prototype = new Person();
var Person = function (name) {
    this.name = name;
};
Person.prototype.getName = function () {
    return this.name;
};
var john = new Person("John");
alert(john.getName());
Person.prototype.sayMyName = function () {
    alert('Hello, my name is ' + this.getName());
};
john.sayMyName();
var Customer = function (name) {
    this.name = name;
};
Customer.prototype = new Person();

var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
Customer.prototype.setAmountDue = function (amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function () {
    return this.amountDue;
};
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());

As far as I understand var Person = function (name) {...}; is defining a constructor function capable of building Person Objects. So there is no Object yet, only the anonymous constructor function is assigned to Person. This is a very good explanation: helephant.com/2008/08/how-javascript-objects-work

I notice that this answer also doesn't mention that by using "new Person()" as the prototype, you are actually setting the "name" instance property of "Person" to be a static property of "Customer" (so all Customer instances will have the same property). While it's a good basic example, DON'T DO THAT. :) Create a new anonymous function to act as a "bridge" by setting it's prototype to "Person.prototype", then create an instance from it and set "Customer.prototype" to that anonymous instance instead.

I think the answers on stackoverflow are not only interesting to the original poster, but also to a big community of other people lurking or coming from searches. And I've been one of them and I had benefit from old posts. I think I could contribute to the other answers adding some code examples. About your question: if you leave out the new, it doesn't work. when I call myCustomer.sayMyName() it returns "myCustomer.sayMyName is not a function". The easiest way is experiment with firebug and see what happens.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.

In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

Until now I've been extending the base object, now I create another object and then inheriting from Person.

WARNING: This answer neglects the fact that the parent class constructor is not called on a per instance basis. The only reason it works is because he did the exact same thing (setting the name) in both the child and parent constructor. For a more in depth explanation on common mistakes made when attempting inheritance in JavaScript (and a final solution), please see: this stack overflow post

While as said I can't call setAmountDue(), getAmountDue() on a Person.

Note
Rectangle 27 1

How does JavaScript .prototype work?


Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

@John: yes, it's wrong - only function objects have a predefined prototype property, so your code will throw an error, eg 'obj.prototype is undefined' in FF

Every JavaScript object has an internal property called [[Prototype]]. If you look up a property via obj.propName or obj['propName'] and the object does not have such a property - which can be checked via obj.hasOwnProperty('propName') - the runtime looks up the property in the object referenced by [[Prototype]] instead. If the prototype-object also doesn't have such a property, its prototype is checked in turn, thus walking the original object's prototype-chain until a match is found or its end is reached.

I hate non standard things, especially in programming languages, why is there even a proto when it's clearly not needed?

I think this is what it means to have function objects as first-class citizens.

Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the constructor function's prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.

So, I'm I doing something wrong by defining new properties on the prototype property in my short snippet?

Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named __proto__. In general, it's only possible to set an object's prototype during object creation: If you create a new object via new Func(), the object's [[Prototype]] property will be set to the object referenced by Func.prototype.

This allows to simulate classes in JavaScript, although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based:

note that the use of [[Prototype]] is deliberate - ECMA-262 encloses names of internal properties with double square brackets

Note
Rectangle 27 1

How does JavaScript .prototype work?


UserDefinedFunction.prototype={constructor:UserDefinedFunction}
function UserDefinedFunction(){}
UserDefinedFunction.prototype=null// Can be set to any non object value (number,string,undefined etc.)

var o=new UserDefinedFunction()
alert(Object.getPrototypeOf(o)==Object.prototype)   //Displays true
alert(o.constructor)    //Displays Function Object
function UserDefinedFunction()
{
}
var Object= new Function ([native code for object Object])
var String= new Function ([native code for object String])
var Number= new Function ([native code for object Number])
var Boolean= new Function ([native code for object Boolean])
var Array= new Function ([native code for object Array])
var RegExp= new Function ([native code for object RegExp])
var Function= new Function ([native code  for object Function])
var UserDefinedFunction= new Function ("user defined code")
var a=String() // Create a new Non Object string. returns a typeof==='string' 
var a=Number() // Create a new Non Object Number. returns a typeof==='number'
var a=Boolean() //Create a new Non Object Boolean. returns a typeof==='boolean'
var a=UserDefinedFunction() //may or may not create an object of type UserDefinedFunction() based on how it is defined.
var a=new Object() or var a=Object() or var a={} //Create object of type Object
var a=new String() //Create object of type String
var a=new Number() //Create object of type Number
var a=new Boolean() //Create object of type Boolean
var a=new Array() or var a=Array() or var a=[]  //Create object of type Array
var a=new RegExp() or var a=RegExp() //Create object of type RegExp
var a=new UserDefinedFunction()
var b=new Math() //error. Math is not typeof==='function'
var b=new a() //error. a is not typeof==='function'
var o=Object.create(null)
alert(Object.getPrototypeOf(o)) //Displays null
var o=Starting object;

do {
    alert(o + "\n" + Object.getOwnPropertyNames(o))

}while(o=Object.getPrototypeOf(o))

is created in the newly created object that references the object referenced by Constructor function's current prototype object.

when a new object is created (using new operator)it inherits all properties and methods from Constructor function's current prototype object i.e. an

  • All the other built in objects that can create new objects by using new operator
  • Object created with new or Object.create -> One or More prototype chains -> Object.prototype -> null

All the Function type objects are actually instances of the built in JavaScript object Function (including the Function object i.e it is recursively defined). It is as if the these objects have been defined in the following way

All the concept explained above can be a little daunting to understand without any supporting code. Please go through the following code line by line to understand the concept. Try to execute it to have a better understanding.

Also notice that Object,Array and RegExp functions can create a new object without even using operator new. However the follwing ones don't.

Also, every object that is created (Function type or Non Function type) has a "constructor" property which is inherited from the object referenced by prototype property of the Constructor function. By default this "constructor" property references the Constructor function that created it (if the Constructor Function's default "prototype" is not changed).

As mentioned, the Function type objects can further create new objects using the new operator. For e.g an object of type Object, String, Number, Boolean, Array, RegExp Or UserDefinedFunction can be created by using

Every Constructor/Function (whether built in or user defined) when defined automatically has a property called "prototype" whose value by default is set as an object. This object itself has a property called "constructor" which by default references back the Constructor/Function .

Following are the Non object data types

Following in the summary of this article

For Non Function type objects (e.g Javascript Built in Math object) the constructor function is the function that created it. For Math object it is function Object(){}.

For all Function type objects the constructor function is always function Function(){}

For creating an object without any prototype use the following:

One might think that setting the prototype property of the Constructor to null shall create an object with a null prototype. However in such cases the newly created object's prototype is set to Object.prototype and its constructor is set to function Object. This is demonstrated by the following code

Since the Function type objects can create new objects they are also called Constructors.

The Function type objects are the ones that return the string 'function' with typeof operator. All the user defined functions and all the JavaScript built in objects that can create new objects by using new operator fall into this category. For eg.

The built in object Math is typeof==='object'. Hence a new object of type Math cannot be created by new operator.

The object datatypes can be further divided into two types

The objects thus created are all Non Function type objects and return their typeof==='object'. In all these cases the object "a" cannot further create objects using operator new. So the following is wrong

The prototype chain for various objects work out as follows.

The prototype chain of every object ultimately traces back to Object.prototype (which itself does not have any prototype object) . Following code can be used for tracing the prototype chain of an object

The string,number and boolean data types can be represented both as Objects and Non objects.When they are represented as objects their typeof is always === 'object'. We shall come back to this once we understand the object data types.

The user defined functions are special case.

These data types return following when you use the typeof operator

This "internal reference" that is created in the object for referencing inherited properties is known as the object's prototype (which references the object referenced by Constructor's "prototype" property but is different from it). For any object (Function or Non Function) this can be retrieved using Object.getPrototypeOf() method. Using this method one can trace the prototype chain of an object.

This article is long. But I am sure it will clear most of your queries regarding the "prototypical" nature of JavaScript Inheritance. And even more. Please read the complete article.

typeof "string literal" (or a variable containing string literal) === 'string'

typeof 5 (or any numeric literal or a variable containing numeric literal or NaN or Infynity) === 'number'

typeof undefined (or an undefined variable or a variable containing undefined) === 'undefined'

Note
Rectangle 27 1

How does JavaScript .prototype work?


//Create a new object of type Customer by defining its constructor. It's not 
//related to Person for now.
var Customer = function(name) {
    this.name = name;
};

//Now I link the objects and to do so, we link the prototype of Customer to 
//a new instance of Person. The prototype is the base that will be used to 
//construct all new instances and also, will modify dynamically all already 
//constructed objects because in JavaScript objects retain a pointer to the 
//prototype
Customer.prototype = new Person();     

//Now I can call the methods of Person on the Customer, let's try, first 
//I need to create a Customer.
var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();

//If I add new methods to Person, they will be added to Customer, but if I
//add new methods to Customer they won't be added to Person. Example:
Customer.prototype.setAmountDue = function(amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function() {
    return this.amountDue;
};

//Let's try:       
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());
//Define a functional object to hold persons in JavaScript
var Person = function(name) {
  this.name = name;
};

//Add dynamically to the already defined object a new getter
Person.prototype.getName = function() {
  return this.name;
};

//Create a new object of type Person
var john = new Person("John");

//Try the getter
alert(john.getName());

//If now I modify person, also John gets the updates
Person.prototype.sayMyName = function() {
  alert('Hello, my name is ' + this.getName());
};

//Call the new method on john
john.sayMyName();
//The following statement generates an error.
john.setAmountDue(1000);
Customer.prototype = Object.create(Person.prototype)
Customer.prototype = new Person();
var Person = function (name) {
    this.name = name;
};
Person.prototype.getName = function () {
    return this.name;
};
var john = new Person("John");
alert(john.getName());
Person.prototype.sayMyName = function () {
    alert('Hello, my name is ' + this.getName());
};
john.sayMyName();
var Customer = function (name) {
    this.name = name;
};
Customer.prototype = new Person();

var myCustomer = new Customer('Dream Inc.');
myCustomer.sayMyName();
Customer.prototype.setAmountDue = function (amountDue) {
    this.amountDue = amountDue;
};
Customer.prototype.getAmountDue = function () {
    return this.amountDue;
};
myCustomer.setAmountDue(2000);
alert(myCustomer.getAmountDue());

As far as I understand var Person = function (name) {...}; is defining a constructor function capable of building Person Objects. So there is no Object yet, only the anonymous constructor function is assigned to Person. This is a very good explanation: helephant.com/2008/08/how-javascript-objects-work

I notice that this answer also doesn't mention that by using "new Person()" as the prototype, you are actually setting the "name" instance property of "Person" to be a static property of "Customer" (so all Customer instances will have the same property). While it's a good basic example, DON'T DO THAT. :) Create a new anonymous function to act as a "bridge" by setting it's prototype to "Person.prototype", then create an instance from it and set "Customer.prototype" to that anonymous instance instead.

I think the answers on stackoverflow are not only interesting to the original poster, but also to a big community of other people lurking or coming from searches. And I've been one of them and I had benefit from old posts. I think I could contribute to the other answers adding some code examples. About your question: if you leave out the new, it doesn't work. when I call myCustomer.sayMyName() it returns "myCustomer.sayMyName is not a function". The easiest way is experiment with firebug and see what happens.

In JavaScript you first create an object (there is no concept of class), then you can augment your own object or create new objects from it. It's not difficult, but a little foreign and hard to metabolize for somebody used to the classical way.

In a language implementing classical inheritance like Java, C# or C++ you start by creating a class--a blueprint for your objects--and then you can create new objects from that class or you can extend the class, defining a new class that augments the original class.

Until now I've been extending the base object, now I create another object and then inheriting from Person.

WARNING: This answer neglects the fact that the parent class constructor is not called on a per instance basis. The only reason it works is because he did the exact same thing (setting the name) in both the child and parent constructor. For a more in depth explanation on common mistakes made when attempting inheritance in JavaScript (and a final solution), please see: this stack overflow post

While as said I can't call setAmountDue(), getAmountDue() on a Person.

Note
Rectangle 27 1

How does JavaScript .prototype work?


Every JavaScript object has an internal property called [[Prototype]]. If you look up a property via obj.propName or obj['propName'] and the object does not have such a property - which can be checked via obj.hasOwnProperty('propName') - the runtime looks up the property in the object referenced by [[Prototype]] instead. If the prototype-object also doesn't have such a property, its prototype is checked in turn, thus walking the original object's prototype-chain until a match is found or its end is reached.

I hate non standard things, especially in programming languages, why is there even a proto when it's clearly not needed?

I think this is what it means to have function objects as first-class citizens.

Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the constructor function's prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.

So, I'm I doing something wrong by defining new properties on the prototype property in my short snippet?

Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named __proto__. In general, it's only possible to set an object's prototype during object creation: If you create a new object via new Func(), the object's [[Prototype]] property will be set to the object referenced by Func.prototype.

This allows to simulate classes in JavaScript, although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based:

note that the use of [[Prototype]] is deliberate - ECMA-262 encloses names of internal properties with double square brackets

Note
Rectangle 27 1

How does JavaScript .prototype work?


Every JavaScript object has an internal property called [[Prototype]]. If you look up a property via obj.propName or obj['propName'] and the object does not have such a property - which can be checked via obj.hasOwnProperty('propName') - the runtime looks up the property in the object referenced by [[Prototype]] instead. If the prototype-object also doesn't have such a property, its prototype is checked in turn, thus walking the original object's prototype-chain until a match is found or its end is reached.

I hate non standard things, especially in programming languages, why is there even a proto when it's clearly not needed?

I think this is what it means to have function objects as first-class citizens.

Just think of constructor functions as classes and the properties of the prototype (ie of the object referenced by the constructor function's prototype property) as shared members, ie members which are the same for each instance. In class-based systems, methods are implemented the same way for each instance, so methods are normally added to the prototype, whereas an object's fields are instance-specific and therefore added to the object itself during construction.

So, I'm I doing something wrong by defining new properties on the prototype property in my short snippet?

Some JavaScript implementations allow direct access to the [[Prototype]] property, eg via a non-standard property named __proto__. In general, it's only possible to set an object's prototype during object creation: If you create a new object via new Func(), the object's [[Prototype]] property will be set to the object referenced by Func.prototype.

This allows to simulate classes in JavaScript, although JavaScript's inheritance system is - as we have seen - prototypical, and not class-based:

note that the use of [[Prototype]] is deliberate - ECMA-262 encloses names of internal properties with double square brackets

Note