this code is only example. I try to understand Object.create.
function Animal {}
var cat = new Animal();
I want to create 100 animals and add to constructor some method for example saySomething(). So I add it to prototype, and I know that my method will be created only once and every instance has access to it:
Animal.prototype.saySomething = function(voice) {
console.log(voice)
}
But what when I create objects like that:
var Animal = {
saySomething: function(voice) {
console.log(voice)
}
}
var cat = Object.create(Animal);
var dog = Object.create(Animal);
...
When I create objects like that, is saySomething method is created for each instance separately? How can I add this method to the Animal object in the same way as previous? I'm confused :/ Please help.
By the looks of things the method is created only on the prototype.
dog.__proto__.saySomething
- is defined so it's defined on the prototype
To double check dog.hasOwnProperty('saySomething')
returns false which either indicates the property isn't enumerable or is defined on the prototype.
If you want to then add methods to you cat or dog and ensure only one copy of properties are created you can just add them to and instance then call Object.create on the instance.
var Animal = {
saySomething: function(voice) {
console.log(voice)
}
}
var cat = Object.create(Animal);
var dog = Object.create(Animal);
cat.saySomething = function(){
console.log('meow')
};
var catInstance = Object.create(cat);
catInstance.saySomething(); // 'meow'
typeof catInstance.__proto__.saySomething == "function" // true