javascript - 为什么 myObject.function() 抛出 'is not a function' 错误? (尝试学习函数实例化)

标签 javascript prototype

我正在尝试使用函数创建一个类,并为其提供一些 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/

相关文章:

php - 访问另一页面后保留浏览器滚动位置

javascript - 将闭包转换为 es6 模块

javascript - 动态添加系列

javascript - 为什么使用原型(prototype)而不是方法

uitableview - iOS Storyboard: set a background color to prototype cell

javascript - 创建具有多个基本 URL 的 Javascript API 类

javascript - 如何使用 javascript 和/或 jQuery 获取特定类中所有元素的数组?

javascript - 私有(private)对象属性

javascript - 定时器开始暂停和恢复

javascript - 在 Javascript 中输入发送键只能运行一次