简体   繁体   中英

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."

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.

The problem is here: ninja.prototype.swingSword()

Yous have to call it: ninja.swingSword()

If you want to explicitly invoke the prototype method, I believe this is the syntax:

var ninja = new Ninja();
console.log(Ninja.prototype.swingSword.call(ninja), "Calling the instance method, not the prototype method.");

So the prototype isn't hanging off the ninja variable. It's hanging off the Ninja type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM