简体   繁体   English

通过原型添加方法

[英]Adding a method through the prototype

I am trying to add a height method but now when i call it without the () . 我正在尝试添加一个高度方法,但现在我在没有()情况下调用它。 How can i use this it as a method the benji.height() method?I mean with the Parenthesis at the end? 我如何使用它作为benji.height()方法的方法?我的意思是最后用括号?

function Dog() {
    this.tail = true;
    this.height = 33;

}
 var benji = new Dog();
 var rusty = new Dog();

 Dog.prototype.height = function() {
     return "the height is " +  this.height + " cms";
 };

console.log(benji.height);

You have a field named height and you are trying to add a method called height . 您有一个名为height的字段,并且您正在尝试添加名为height的方法。
You need to give it an unambigious name and it will work. 你需要给它一个明确的名称,它会起作用。

 function Dog() { this.tail = true; this.height = 33; } var benji = new Dog(); var rusty = new Dog(); Dog.prototype.getHeight = function() { return "the height is " + this.height + " cms"; }; document.body.innerHTML = "<b>height:</b> " + (benji.height) + "<br/>"; document.body.innerHTML += "<b>getHeight():</b> " + benji.getHeight(); 

So you have height variable in both the place Object and object prototype. 因此,在Object和object原型中都有高度变量。 So according to prototype chain it will first lookup in Object and then its prototype. 因此,根据原型链,它将首先在Object中查找,然后在原型中查找。

Here 这里

function Dog() {
    this.tail = true;
    this.height = 33;

}

height variable will store in object So it will find height which is not a function that a reason you are not able to call as benji.height(); 高度变量将存储在对象中所以它将找到高度,这不是一个你不能称为benji.height();的原因的函数benji.height();

So as other user suggest just change the name of function you can call it as you want. 因此,正如其他用户建议只需更改功能名称,您可以根据需要调用它。

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

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