What is the recommended way to configure toString? Using Symbol.toStringTag or overriding toString?

I was confused about what to implement, firstly, my module will use Babel, so there is no problem with implementing ES6 functions, and secondly, I will use the class construct to create a class, and not the old prototype method. So now I'm confused if I go toString (this is the old way) or just implement Symbol.toStringTag, like what is said in this MDN documentation, https://developer.mozilla.org/en-US/docs/Web/ JavaScript / Reference / Global_Objects / Symbol / toStringTag So what is the recommended way?

+5
source share
1 answer

They are for different things in their entirety.

If you are trying to determine the string version of your object, specify the toString method.

If you are trying to add information to your class that Object.prototype.toString will use to construct the string "[object XYZ]" , specify a method whose name is the value of Symbol.toStringTag .

Here is an illustration of the difference:

 class Example { constructor(x) { this.x = x; } toString() { return `Example[x=${this.x}]`; } get [Symbol.toStringTag]() { return "Example"; } } const e = new Example(42); console.log(e.toString()); // Example[x=42] console.log(String(e)); // Example[x=42] console.log(Object.prototype.toString.call(e)); // [object Example] 

If we did not indicate that get [Symbol.toStringTag] , the last line prints "[object Object]" and not "[object Example]" .

Please note that it should not be a getter, it may be a data property. Since you are using Babel, you can define it like this if you enable Public Class Fields support (currently stage 2):

 class Example { constructor(x) { this.x = x; } toString() { return `Example[x=${this.x}]`; } [Symbol.toStringTag] = "Example"; } 

... although, of course, it would be available for recording. As an alternative:

 class Example { constructor(x) { this.x = x; } toString() { return `Example[x=${this.x}]`; } } Object.defineProperty(Example.prototype, Symbol.toStringTag, { value: "Example" }); 
+8
source

Source: https://habr.com/ru/post/1265678/


All Articles