As Sean Vieira explained the first method is not the same as the second method. In the first method the instance inherits from Person.prototype. In the second method the instance inherits directly from Object.prototype.
Method 1:
null
^
|
| __proto__
|
+------------------+
| Object.prototype |
+------------------+
^
|
| __proto__
|
+------------------+
| Person.prototype |
+------------------+
^
|
| __proto__
|
+------------------+
| person |
+------------------+
Method 2:
null
^
|
| __proto__
|
+------------------+
| Object.prototype |
+------------------+
^
|
| __proto__
|
+------------------+
| person |
+------------------+
Interestingly the above diagrams show you that objects inherit from other objects in JavaScript, and not from constructors. Hence when you create new Person the instance inherits from Person.prototype, not from Person itself.
How is this relevant information? For starters it demonstrates that you don't need to create a constructor to creates instances of an object. Instead you directly create the prototype object as follows:
var person = {
create: function (name, gender) {
var person = Object.create(this);
person.gender = gender;
person.name = name;
return person;
},
speak: function () {
alert("My name is " + this.name + ".");
}
};
In the above example person is equivalent to Person.prototype. You may now create an instance of person as follows:
var bob = person.create("Bob", "M");
The prototype chain of bob will look like this:
null
^
|
| __proto__
|
+------------------+
| Object.prototype |
+------------------+
^
|
| __proto__
|
+------------------+
| person |
+------------------+
^
|
| __proto__
|
+------------------+
| bob |
+------------------+
So why should you create objects like this instead?
- It looks cleaner. Everything is encapsulated in a single object literal.
- It's easier to understand that objects inherit from objects. No constructors needed.
- You don't need to use
new to create an instance. This solves a lot of problems.
For more information about this pattern read my blog post on "Why Prototypal Inheritance Matters".