简体   繁体   English

为什么调用此原型方法无效?

[英]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. 我正在通过各种教程快速学习javascript,而我刚买了一本中高级书。 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() 所以我需要知道为什么这个原型方法不返回新值,或者当我在函数Ninja()的第一个声明之外执行该原型方法时会发生什么

...This returns cannot return property 'swingSword' I have one request though sorry. ...此返回无法返回属性“ swingSword”,尽管抱歉,我有一个请求。 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 . ninja.prototype.swingSword()不起作用,因为ninja.prototypeundefined I think you meant ninja.swingSword() . 我认为您的意思是ninja.swingSword()

First we need to understand that, JavaScript will look for attributes, first in the current object. 首先,我们需要了解,JavaScript将首先在当前对象中查找属性。 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. 在这种情况下,由于您向该(当前实例)添加了swingSwordthis当您调用ninja.swingSword() ,将在当前实例中执行swingSword

The problem is here: ninja.prototype.swingSword() 问题在这里:ninja.prototype.swingSword()

Yous have to call it: ninja.swingSword() 您必须调用它: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. 因此,原型并未脱离ninja变量。 It's hanging off the Ninja type. 它是Ninja式的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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