繁体   English   中英

通过原型添加方法

[英]Adding a method through the prototype

我正在尝试添加一个高度方法,但现在我在没有()情况下调用它。 我如何使用它作为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);

您有一个名为height的字段,并且您正在尝试添加名为height的方法。
你需要给它一个明确的名称,它会起作用。

 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(); 

因此,在Object和object原型中都有高度变量。 因此,根据原型链,它将首先在Object中查找,然后在原型中查找。

这里

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

}

高度变量将存储在对象中所以它将找到高度,这不是一个你不能称为benji.height();的原因的函数benji.height();

因此,正如其他用户建议只需更改功能名称,您可以根据需要调用它。

暂无
暂无

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

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