在 ES6 中扩展字符串时出错

The error when extending String in ES6

本文关键字:出错 字符串 扩展 ES6      更新时间:2023-09-26

 'use strict';
 class ReverseString extends String {
   reversed() {
     let res = '';
     for (let i = this.length - 1; i >= 0; --i) {
       res += this[i];
     }
     return res;
   }
 }
 let rs = new ReverseString("wangyang");
 console.log(rs.reversed());

当我运行此代码时,我遇到一个错误:

C:'Users'elqstux'Desktop>node wy.js
C:'Users'elqstux'Desktop'wy.js:14
console.log(rs.reversed());
               ^
TypeError: rs.reversed is not a function
    at Object.<anonymous> (C:'Users'elqstux'Desktop'wy.js:14:16)
    at Module._compile (module.js:398:26)
    at Object.Module._extensions..js (module.js:405:10)
    at Module.load (module.js:344:32)
    at Function.Module._load (module.js:301:12)
    at Function.Module.runMain (module.js:430:10)
    at startup (node.js:141:18)
    at node.js:980:3

我找不到此错误的根本原因。

console.log(rs);的输出是String {0: "w", 1: "a", 2: "n", 3: "g", 4: "y", 5: "a", 6: "n", 7: "g", length: 8, [[PrimitiveValue]]: "wangyang"}]

这是我的节点版本:

C:'Users'elqstux'Desktop>node -v
v5.3.0

String 目前在 Node 5.3 中不可子类化,根据:

https://kangax.github.io/compat-table/es6/#test-miscellaneous_subclassables

您的示例应该在 Firefox 45+ 和 Edge 13+ 上运行良好