如何制作方法" toString"私人的?

时间:2018-05-12 17:17:29

标签: javascript

" Weapon"实现方法" toString",这对于Object.keys()是不可用的。



function Weapon(name,damage) {
    this.name = name;
    this.damage = damage;
    this.toString = function () {
        return this.name + this.damage + " damage";
    }
}
var bow = new Weapon(' Golden bow, ',20);
var sword = new Weapon(' Magic sword, ', 40);
console.log(bow.toString());
console.log(sword.toString());
Object.defineProperty(Weapon, "toString", {enumerable: false});




1 个答案:

答案 0 :(得分:8)

来自MDN关于Object.keys()

  

Object.keys()返回一个数组,其元素是与直接在对象上找到的可枚举属性相对应的字符串。

所以要么使属性不可枚举

function Weapon(name,damage) {
    this.name = name;
    this.damage = damage;
    Object.defineProperty(this, 'toString', {
      value: function () {
        return this.name + this.damage + " damage";
      },
      // enumerable: false, // is implicitly set
    });
}

或者通过在原型上定义 而不是 属性

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

Weapon.prototype.toString = function () {
  return this.name + this.damage + " damage";
};

如果您使用class语法,则“免费”获得两者:

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

  toString()
    return this.name + this.damage + " damage";
  }
}

toString将在原型上定义,并且不会被枚举。