我正在尝试使用函数创建一个类,并为其提供一些 Prop 和方法。如果我在 C# 中以基于类的方式做同样的事情并调用该方法,这将工作正常,但在 JS 中它会给我一个错误。我的问题是为什么它的行为方式不同。
代码片段:
function Animal (name) {
let animal = {}
animal.name = name;
animal.eat = function (){
console.log(`${this.name} is eating`)
}
}
let myAnimal = new Animal('dog');
console.log(myAnimal.eat()); //Uncaught TypeError: myAnimal.eat is not a function at proto.js:11
最佳答案
这将是在 JavaScript 中实现这一目标的典型方法:
function Animal(name) {
this.name = name;
}
Animal.prototype.eat = function() {
console.log(`${this.name} is eating`)
}
new Animal('Pooch').eat();
或者引入classes (自 ECMAScript 2015 起):
class Animal {
constructor(name) {
this.name = name;
}
eat() {
console.log(`${this.name} is eating`)
}
}
new Animal('Pooch').eat();
关于javascript - 为什么 myObject.function() 抛出 'is not a function' 错误? (尝试学习函数实例化),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56591752/