2016-01-15 16 views
6

L'errore quando si estende per archi 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());

quando ho eseguito questo codice, incontro un errore:

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 

non riesco a trovare la causa principale di questo errore.

l'uscita di console.log(rs); è String {0: "w", 1: "a", 2: "n", 3: "g", 4: "y", 5: "a", 6: "n", 7: "g", length: 8, [[PrimitiveValue]]: "wangyang"}].

Qui è la mia versione nodo:

C:\Users\elqstux\Desktop>node -v 
v5.3.0 
+0

Questa domanda [è già stata sollevata] (http://stackoverflow.com/questions/34605185/failing-to-subclass-builtin-string-object). Fondamentalmente il nodo non supporta completamente i built-in di sottoclassi. Il problema principale è che non crea mai realmente un 'instanceof ReverseString'. Node vede 'rs' come' String' – CodingIntrigue

risposta

2

String attualmente non derivabile in sotto classi nel nodo 5.3, secondo:

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

Il vostro esempio dovrebbe funzionare bene su Firefox 45 e Edge 13 +

+0

Posso confermare che non funziona in Webkit, ma funziona in Edge! – CoderPi

+0

Says * Flag: il supporto per questa funzione richiede in modo non corretto la modalità rigorosa *. In realtà non funziona con alcun flag, o modalità strict – CodingIntrigue

+0

@RGraham Probabilmente è perché il Node 5 non supporta 'class' al di fuori della modalità strict. –

Problemi correlati