How for "Weapon" implement the method "toString", which will be unavailable for 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});
From MDN about Object.keys()
:
Object.keys()
returns an array whose elements are strings corresponding to the enumerable properties found directly upon object.
So either make the property non-enumerable:
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
});
}
Or make it not an "own" property by defining it on the prototype:
function Weapon(name,damage) {
this.name = name;
this.damage = damage;
}
Weapon.prototype.toString = function () {
return this.name + this.damage + " damage";
};
You get both "for free" if you use class
syntax:
class Weapon {
constructor(name,damage) {
this.name = name;
this.damage = damage;
}
toString()
return this.name + this.damage + " damage";
}
}
toString
will be defined on the prototype and it won't be enumerable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With