简体   繁体   English

向原型添加功能不起作用

[英]Adding a function to a prototype does not work

I am trying to add a function to prototype like this 我正在尝试向原型添加一个功能

function Dog(name, breed) {
    this.name = name;
    this.breed = breed;
}

function barkWithMe() {
    console.log("woof woof i am " + this.name);
}
Dog.prototype.bark = barkWithMe();

var snoopy = new Dog();
snoopy.bark();

But it displays an error 但显示错误

Uncaught TypeError: snoopy.bark is not a function

Please tell me where am I wrong. 请告诉我我哪里错了。 Thanks. 谢谢。

This line evaluates the function and sets the return value undefined to Dog.prototype.bark : 此行评估函数并将undefined的返回值设置为Dog.prototype.bark

Dog.prototype.bark = barkWithMe();

Change it to: 更改为:

Dog.prototype.bark = barkWithMe;

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

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