EDIT: This answer was originally a response to @ jordancpaul's answer, which he has since corrected. I will leave a part of my answer that will help explain the important difference between prototype properties and instance properties:
In some cases, properties are shared among all instances, and you need to be very careful when you declare prototype properties. Consider this example:
Person.prototype.favoriteColors = []; //Do not do this!
Now, if you create a new instance of Person using either Object.create
or new
, it does not work as you might expect ...
var jim = new Person("Jim",13); jim.favoriteColors.push('red'); var tim = new Person("Tim",14); tim.favoriteColors.push('blue'); console.log(tim.favoriteColors);
This does not mean that you can never declare the properties of a prototype, but if you do, you and every developer who works on your code should be aware of this trap. In this case, if you prefer to declare the properties of the prototype for any reason, you can do:
Person.prototype.favoriteColors = null
And initialize it with an empty array in the constructor:
var Person = function(name, age) { ... this.favoriteColors = []; }
The general rule when using this method is that the default values ββfor simple literal properties (strings, numbers, logical values) can be set directly on the prototype, but any property that inherits from Object (including arrays and dates) must be set to null and then initialized in the constructor.
A safer way is to only declare methods in the prototype and always declare properties in the constructor.
Anyway, the question was about Object.create ...
The first argument passed to Object.create is set as the prototype of the new instance. Best use:
var person = { initialize: function(name, age) { this.name = name; this.age = age; return this; }, toString: function() { return this.name + ', ' + this.age; } }; var tim = Object.create(person).initialize("Tim",14);
Now the result will be the same as in your first example.
As you can see, this is a different philosophical approach from the more classic OOP style in Javascript. With Object.create, the emphasis is on creating new objects from existing objects, not on the constructor. Initialization becomes a separate step.
Personally, I have mixed feelings about the Object.create approach; this is very nice for inheritance because of the second parameter, which you can use to add additional properties to an existing prototype, but it is also more detailed and makes instance checks no longer work (an alternative in this example would be to check person.isPrototypeOf(tim)
).
The main reason I say that Object.create is verbose due to the second parameter, but there are some useful libraries that address:
https://github.com/Gozala/selfish
https://github.com/Raynos/pd
(other)
Hope this was more informative than entanglement!