对于“武器”,如何实现方法“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});
最佳答案
从MDN关于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
});
}
或通过在原型(prototype)上对其进行定义,使其成为而不是“拥有”属性:
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
将在原型(prototype)上定义,并且无法枚举。