我正在尝试运行使用构造函数创建的对象的函数。但是,我无法这样做,因为我不断收到错误提示“TypeError: mutant_cat.meow is not a function。 (在'mutant_cat.meow()'中,'mutant_cat.meow'是未定义的)”。 这是我的构造函数:
function Cat(legs, sound) {
this.legs = legs;
this.sound = sound;
var meow = function() {
document.write(sound);
}
}
这是我创建对象并尝试运行其功能的地方:
var mutant_cat = new Cat(5, "eeeeeee");
mutant_cat.meow();
非常感谢任何帮助。
最佳答案
这应该可以解决它。您需要使用“this”使函数成为对象的属性。
function Cat(legs, sound) {
this.legs = legs;
this.sound = sound;
this.meow = () => {
document.write(this.sound);
}
}
如果您希望所有的猫都发出喵喵声,那么您最好使用原型(prototype)函数,因为这是内存优化的并且是所有猫实例之间的共享函数,而不是每个猫都有自己重复的喵喵函数。
您可以在此处阅读有关原型(prototype)函数的更多信息:https://www.w3schools.com/js/js_object_prototypes.asp
关于javascript - 无法运行对象的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56811042/