【问题标题】:JS ES6 Class ToString() Method is not working even with Babel or in ChromeJS ES6 类 ToString() 方法即使在 Babel 或 Chrome 中也不起作用
【发布时间】:2019-01-02 12:50:28
【问题描述】:

对于我下面的代码,我想设置一个默认的 toString() 方法,它会覆盖该类的内置 toString()。但它不起作用,我得到输出“Queue { data: [] }”而不是预期的“Hello This is example”。我查看了一些已经讨论过的关于 SO 的类似问题,但没有帮助。我也尝试过最新版本的 Chrome 并且行为是相同的。我有带有 Babel 6 的 Node 10.13 (babel-node --presets env,stage-2 queue.js)。在这里寻找一些专家意见。

class Queue {
  constructor() {
    this.data = [];
  }
  toString() {
    console.log("Hello This is example");
  }
}

const queue1 = new Queue();
console.log(queue1);

【问题讨论】:

  • 谢谢安德烈亚斯,让 str = queue1 + "";成功了。我真的很想知道为什么 console.log() 不调用它。现在每次我必须控制台记录它时,我都必须在它之前创建 str。
  • 因为在检查(记录)对象时,字符串或多或少是无用的(恕我直言)。

标签: javascript class ecmascript-6


【解决方案1】:

您必须显式或隐式触发.toString() 的调用

console.log(queue1.toString());
console.log(queue1 + "");
console.log([queue1, queue2].join());

.toString() 必须返回字符串表示:

toString() { return "..." }

class Queue {
  constructor() {
    this.data = [];
  }
  toString() {
    return "Hello This is example"; // toString has to return the string representation
  }
}

const queue1 = new Queue();
console.log(queue1 + "");

const queue2 = new Queue();
console.log([queue1, queue2].join());

【讨论】:

  • 使用模板文字是隐式调用 toString 的另一种方式。所以console.log(`${queue1}`) 也应该给你你想要的。
  • @DhruvPrakash 有多种方法可以触发对.toString() 的调用。这些仅作为示例,并非所有可能性的完整列表。
【解决方案2】:

对于我下面的代码,我想设置一个默认的 toString() 方法 覆盖该类的内置 toString()。但它不工作 我得到输出“队列{数据:[]}”而不是预期的“你好 这是示例”。

class Queue {
  constructor() {
    this.data = [];
  }
  toString() {
    console.log("Hello This is example");
  }
}

const queue1 = new Queue();
console.log(queue1);

在上面的代码中,toString 方法不会覆盖类的toString 方法。为什么?因为类的toString返回一个字符串。

在您的代码中,console.log("Hello This is example"); 不返回任何值。这就是您获得输出的原因:Queue { data: [] }。这是默认输出。如果您从 Queue 类中删除 toString 方法,则语句 console.log(queue1); 仍将打印:Queue { data: [] }

要将Queue 类对象表示为字符串值,您需要编写如下代码:

toString() {
    return "Hello this is an example";
}

要在您的应用程序中使用toString,您可以尝试下面任何#2 或#3 行的代码,它会打印:“Hello this is an example”。

const queue1 = new Queue();
console.log(queue1); // #2
console.log(queue1.toString()); // #3

另请参阅link Object.prototype.toString()

【讨论】:

  • console.log(queue1); // #2 仅适用于某些环境
  • Tnks 用于输入,即使在我从 ToString() 方法返回字符串后,ToString() 仍然无法正常工作,但是 andreas 和 dhruvPrakash 的上述答案完美无缺。我在 console.log() 中使用了 queue1 + ""
  • 那么@Bergi 所说的一定是真的(“#2 仅适用于某些环境”)。该代码对我来说很好,所以我发布了我看到的答案。感谢 cmets。
猜你喜欢
  • 2020-01-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-06-03
  • 2011-07-11
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
相关资源
最近更新 更多