Search code examples
javascriptinheritanceprototypeprototypal-inheritance

Why doesn't calling this prototype method work?


I am learning javascript quite quickly through various tutorials, and I just bought a mid-high level book. And I am quickly realize I actually know almost nothing. So I need to know why this prototyped method isn't returning the new value, or what is happening with the prototyped method when I do it outside the first declaration of the function Ninja()

...This returns cannot return property 'swingSword' I have one request though sorry. Can you tell me in the complicated language saying things like instantiates, inherits, asynchronous or whatever, but also in plain English?

function Ninja() {
    this.swingSword = function() {
        return true;
    };
}

Ninja.prototype.swingSword = function() {
    return false;
};

var ninja = new Ninja();
console.log(ninja.prototype.swingSword());, ///Edit "Calling the prototype method. Not the instance."

Solution

  • ninja.prototype.swingSword() will not work, as ninja.prototype is undefined. I think you meant ninja.swingSword().

    First we need to understand that, JavaScript will look for attributes, first in the current object. Only if it doesn't find, it goes to the prototype chain.

    In this case, since you added swingSword to this (current instance), when you invoke ninja.swingSword(), the swingSword in the current instance will be executed.