Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make the method "toString" private?

Tags:

javascript

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});
like image 208
Igor Shvets Avatar asked Jan 28 '23 03:01

Igor Shvets


1 Answers

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.

like image 140
Felix Kling Avatar answered Jan 30 '23 15:01

Felix Kling