lucasfcosta
lucasfcosta

Reputation: 295

Symbol.toStringTag defined but not being used by .toString method

I was trying to use Symbol.toStringTag in order to get [object Pirate] as a result whenever I try to call .toString on a Pirate instance, but I keep getting [object Object] back!

I already read the ES6 spec for toString and according to it my code should work. Maybe I'm missing something.

The code below is what I expected to happen:

function Pirate(name) {
    this.name = name;
}

Object.defineProperty(Pirate.prototype, Symbol.toStringTag, {
    value: () => 'Pirate'
});

console.log(new Pirate('Jack Sparrow').toString()); // I expected '[object Pirate]'

Am I missing something here? I also checked to see if the Pirate.prototype[Symbol.toStringTag] was being set and it was.

Upvotes: 1

Views: 1088

Answers (3)

Motla
Motla

Reputation: 1232

For use inside a node_module for Electron, I had to set it enumerable to get it work:

Object.defineProperty(Pirate.prototype, Symbol.toStringTag, {
  value: 'Pirate',
  enumerable: true
});

Upvotes: 0

Ravi Tiwari
Ravi Tiwari

Reputation: 962

The problem with your code is this - "toStringTag" is a property rather than an method. So if you change that in your code, it will work correctly.

Here, this is what I mean :

function Pirate(name) {
    this.name = name;
}

Object.defineProperty(Pirate.prototype, Symbol.toStringTag, {
    /* value: () => 'Pirate' */ // change this to property
    value: 'Pirate'
});

console.log(new Pirate('Jack Sparrow').toString()); // I expected '[object Pirate]'

and you will have your result !

Upvotes: 1

YaakovHatam
YaakovHatam

Reputation: 2344

Try this:

function Pirate(name) {
  this.name = name;

  Object.defineProperty(this, Symbol.toStringTag, {
    get: function() {
      return "Pirate";
    }
  });
}
console.log(new Pirate('Jack Sparrow').toString());

Upvotes: 2

Related Questions