You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Animal原型的play方法添加仅通过animal.play.hunt()调用的hunt方法?

实现方案:为Animal原型的play方法添加专属hunt子方法

核心逻辑是JavaScript中函数本身也是对象,可以直接给Animal.prototype.play这个函数对象添加hunt属性(即子方法),这样所有Animal实例的play方法都会附带这个子方法,且只能通过animal.play.hunt()调用,不会挂载到实例本身(无法用animal.hunt()访问)。

基础实现(无需访问实例属性)

保持原有代码不变,直接给play函数添加hunt方法:

function Animal (name, energy) {
  this.name = name
  this.energy = energy
}

Animal.prototype.eat = function (amount) {
  console.log(`${this.name} is eating.`)
  this.energy += amount
}

Animal.prototype.sleep = function (length) {
  console.log(`${this.name} is sleeping.`)
  this.energy += length
}

Animal.prototype.play = function (length) {
  console.log(`${this.name} is playing.`)
  this.energy -= length
}

// 给play函数添加专属hunt方法
Animal.prototype.play.hunt = function() {
  console.log("Hunting while playing!");
}

调用测试

const dog = new Animal("Buddy", 50);

// 正常调用play方法
dog.play(10); // 输出: Buddy is playing.

// 调用play的hunt子方法
dog.play.hunt(); // 输出: Hunting while playing!

// 无法通过实例直接调用hunt
dog.hunt(); // 报错: Uncaught TypeError: dog.hunt is not a function

进阶优化(让hunt能访问实例属性)

如果需要hunt方法能读取或修改Animal实例的name、energy等属性,可以修改play方法的定义,让它返回包含hunt的对象,利用箭头函数继承外层this的特性绑定实例:

function Animal (name, energy) {
  this.name = name
  this.energy = energy
}

Animal.prototype.eat = function (amount) {
  console.log(`${this.name} is eating.`)
  this.energy += amount
}

Animal.prototype.sleep = function (length) {
  console.log(`${this.name} is sleeping.`)
  this.energy += length
}

// 重写play方法,同时支持调用逻辑和返回带hunt的对象
Animal.prototype.play = function(length) {
  // 执行原有的玩耍逻辑(如果传入了时长参数)
  if (typeof length === 'number') {
    console.log(`${this.name} is playing.`);
    this.energy -= length;
  }

  // 返回包含hunt的对象,箭头函数绑定当前实例的this
  return {
    hunt: () => {
      console.log(`${this.name} is hunting while playing!`);
      this.energy -= 15; // 狩猎消耗更多精力
    }
  };
};

优化后调用测试

const cat = new Animal("Whiskers", 60);

// 链式调用:先玩耍再狩猎
cat.play(10).hunt(); 
// 输出:
// Whiskers is playing.
// Whiskers is hunting while playing!

// 直接调用狩猎
cat.play().hunt(); // 输出: Whiskers is hunting while playing!

// 仍然无法通过实例直接调用hunt
cat.hunt(); // 报错: Uncaught TypeError: cat.hunt is not a function

内容的提问来源于stack exchange,提问作者Achint vishwas

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 07:15:39