Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The error when extending String in ES6

 '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());

when i run this code, i meet an error:

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

I can't find the root cause for this error.

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

Here is my node version:

C:\Users\elqstux\Desktop>node -v
v5.3.0
like image 355
BlackMamba Avatar asked Jan 15 '16 12:01

BlackMamba


People also ask

What is error captureStackTrace?

Error.captureStackTrace() A non-standard V8 function that creates the stack property on an Error instance.

How do you return an error in JavaScript?

In JavaScript error message property is used to set or return the error message. Return Value: It returns a string, representing the details of the error.


1 Answers

String is currently not subclassable in Node 5.3, according to:

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

Your example should work fine on Firefox 45+ and Edge 13+

like image 165
Paolo Moretti Avatar answered Oct 16 '22 09:10

Paolo Moretti