This question is related of a book example. I tried to understand it , but at some point it confused me .
In this example we created a constructor function Ninja()
with one property swung
.
We created an object instance of that constructor with the name of ninja1 .
Then we add a method to the prototype of Ninja()
constructor with the name of swingSword()
.
Now if we check ninja1.swingSword()
, we can access that method and everything its fine .
Now here we go , we set a new prototype object for Ninja()
and set a method pierce()
that returns true .
I notice two things so far. First is that ninja1.swingSword()
can still access its "old" prototype . Second is that newly created objects from Ninja() constructor cant access swingSword()
but they can access .pierce() method.
My question is , why ninja1
object cant access pierce()
method ? Is still connected with its prototype to its constructor function which is Ninja()
. I am posting the code to make things clear .
function Ninja() {
this.swung = true;
}
const ninja1 = new Ninja();
Ninja.prototype.swingSword = function() {
return this.swung;
}
console.log(ninja1.swingSword());
Ninja.prototype = {
pierce: function() {
return true;
}
}
console.log('ninj1 object can still use the old prototype even replacing old prototype with new object :' + ninja1.swingSword());
const ninja2 = new Ninja();
console.log(ninja2.pierce());
console.log(ninja1.pierce());
You have changed the whole prototype
object, so it is now has only the pierce
function. But the previously defined object - ninja1
still has a reference to the previous prototype
Ninja.prototype ---> |--------------|
| Swing Swords |
|--------------|
^
| prototype
ninja1 ------------> |its properties|
And when you change the prototype it is now looked like
|--------------|
| Swing Swords |
|--------------|
^
| prototype
ninja1 ------------> |its properties|
Ninja.prototype ---> |--------|
| pierce |
|--------|
^
| prototype
ninja2 ----------> |its properties|
You can see that ninja1
still contains reference to the old prototype object and has nothing with the new prototype. But ninja2
has to the newer prototype object.