Person.prototype.name = 'Nicholas'
and this.name = 'Nicholas'
are NOT the same.
Let's see for ourselves:
var PersonA = function () {
this.name = 'Nicholas';
this.species = 'Homo Sapiens'
return this; // optional
};
var PersonB = function () {
return this;
};
PersonB.prototype.name = 'Nicholas';
PersonB.prototype.species = 'Homo Sapiens'
var personA = new PersonA();
console.log(Object.keys(personA)); // logs ["name", "species"]
var personB = new PersonB();
console.log(Object.keys(personB)); // logs []
console.log(personA.species === personB.species); // logs true
Clearly, personA
has a 2 keys, "name"
and "species"
; while personB
no keys!.
However, the prototype of personB
2 keys, "name"
and "species"
Now, if you create a million objects of PersonA
, each such object would have a
"name": "Nicholas"
and "species": "Homo Sapiens"
key-value pairs.
On the other hand, creating a million objects of PersonB
would be much more memory-efficient as each such object would have no key-value pairs at all! At the same time, both "name"
and "species"
will be available through prototype (prototypal inheritance).
A closer look at refinements:
Lets examine the refinement on an object obj
, say obj.foo
:
- If
"foo"
is a property of obj
, the corresponding value is returned.
- Otherwise, the prototype of
obj
is looked at.
- If that prototype has a property
"foo"
, the corresponding value is returned.
- Otherwise that prototype's prototype is looked at.
- The process continues till we hit
Object.prototype
.
So in terms of memory, PersonB
is superior to PersonA
. This is the beauty of prototypal inheritance.
Hope this helps.