向原型中添加函数是行不通的

Adding a function to a prototype does not work

本文关键字:行不通 函数 添加 原型      更新时间:2023-09-26

我想添加一个功能的原型像这样

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

但是显示错误

Uncaught TypeError: snoopy.bark is not a function

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

这一行计算函数并将返回值undefined设置为Dog.prototype.bark:

Dog.prototype.bark = barkWithMe();

改为:

Dog.prototype.bark = barkWithMe;