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

如何将toString方法设置为私有?如何实现Weapon的toString不被Object.keys()枚举?

问题2:如何为Weapon实现toString方法,使其无法被Object.keys()枚举到?

你原来的代码有个小误区:Object.defineProperty(Weapon, "toString", {enumerable: false})是把方法加到了构造函数本身上,而非实例或原型,所以完全没起到作用。正确的做法分两种:

方式1:挂载到原型上,显式设置不可枚举

function Weapon(name, damage) {
  this.name = name;
  this.damage = damage;
}

// 给原型添加toString,强制设置enumerable为false
Object.defineProperty(Weapon.prototype, 'toString', {
  value: function() {
    return `${this.name} ${this.damage} damage`;
  },
  enumerable: false, // 核心:标记为不可枚举
  writable: true,
  configurable: true
});

const bow = new Weapon('Golden bow', 20);
console.log(bow.toString()); // 输出 "Golden bow 20 damage"
console.log(Object.keys(bow)); // 仅输出 ["name", "damage"],toString不会被枚举

方式2:在构造函数内给实例直接添加(适合每个实例逻辑不同的场景)

function Weapon(name, damage) {
  this.name = name;
  this.damage = damage;
  
  // 给当前实例添加toString,设置不可枚举
  Object.defineProperty(this, 'toString', {
    value: function() {
      return `${this.name} ${this.damage} damage`;
    },
    enumerable: false
  });
}

const bow = new Weapon('Golden bow', 20);
console.log(bow.toString()); // 输出 "Golden bow 20 damage"
console.log(Object.keys(bow)); // 输出 ["name", "damage"],toString不在枚举列表中

另外,如果你用ES6的class语法,原型方法默认就是不可枚举的,直接定义即可:

class Weapon {
  constructor(name, damage) {
    this.name = name;
    this.damage = damage;
  }

  // class的原型方法默认enumerable为false,无需额外设置
  toString() {
    return `${this.name} ${this.damage} damage`;
  }
}

const bow = new Weapon('Golden bow', 20);
console.log(Object.keys(bow)); // 同样仅输出 ["name", "damage"]

内容的提问来源于stack exchange,提问作者Igor Shvets

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 07:35:12