自定义toString的推荐方法是什么?使用Symbol.toStringTag或覆盖toString? [英] What's the recommended way to customize toString? Using Symbol.toStringTag or overriding toString?

查看:129
本文介绍了自定义toString的推荐方法是什么?使用Symbol.toStringTag或覆盖toString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对实现什么感到困惑,首先,我的模块将使用Babel,因此实现ES6功能没有问题,其次,我将使用构造创建类而不是旧的原型方法。所以现在,我很困惑,如果我要覆盖toString(这是旧的方式)或只是实现Symbol.toStringTag,就像这个MDN文档说的那样, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/ toStringTag
那么建议的方式是什么?

I'm confused on what to implement, first, my module will use Babel so there are no problems implementing ES6 features, second, I will use the class construct to create class and not the old prototypal method. So now, I'm confused if I'm going to override toString (which is the old way) or just implement Symbol.toStringTag like what this MDN documentation said, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol/toStringTag So what is the recommended way?

推荐答案

它们完全是针对不同的事情。

They're for different things entirely.

如果您正在尝试定义对象的字符串版本,请提供 toString 方法。

If you're trying to define the string version of your object, provide a toString method.

如果您尝试向您的班级添加信息 Object.prototype.toString 将用于构建其[object XYZ] string,提供一个方法,其名称为 Symbol.toStringTag

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

以下是差异的说明:

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]

如果我们没有提供获取[Symbol.toStringTag] ,最后一行输出[object Object]而不是[object example]

If we hadn't provided that get [Symbol.toStringTag], that last line would output "[object Object]" rather than "[object Example]".

请注意, 不是getter,它可以是数据属性。由于您使用的是Babel,如果您包含公共类字段<,则可以这样定义/ a>支持(目前阶段2):

Note that it doesn't have to be a getter, it can be a data property instead. Since you're using Babel, you could define it like this if you include 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 writable. Alternately:

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

这篇关于自定义toString的推荐方法是什么?使用Symbol.toStringTag或覆盖toString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆