向原型添加功能不起作用

Mar*_*ini 1 javascript

我试图像这样添加一个原型函数

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();
Run Code Online (Sandbox Code Playgroud)

但它显示错误

Uncaught TypeError: snoopy.bark is not a function
Run Code Online (Sandbox Code Playgroud)

请告诉我我哪里错了.谢谢.

Sar*_*ana 6

该行评估函数并将返回值设置undefinedDog.prototype.bark:

Dog.prototype.bark = barkWithMe();
Run Code Online (Sandbox Code Playgroud)

将其更改为:

Dog.prototype.bark = barkWithMe;
Run Code Online (Sandbox Code Playgroud)