I experimented with subclassing the String inline object in ES2015 using Node 5.3.0. I am running code that is not broadcast using a bunch of harmony flags. Here's the full command: node --harmony --harmony_modules --harmony_destructuring --harmony_rest_parameters --harmony_arrow_functions --harmony_spreadcalls --harmony_object --harmony_default_parameters --harmony_new_target --harmony_reflect --harmony_modules ~/t.js
Given that the specification specifically says that the String object is subclass (see Section 21.1.1 The String Constructor ), I struggle to understand that this is what I am doing wrong or an error in Node, or maybe even V8.
Code to reproduce the problem follows:
'use strict'; class Str extends String { capitalize() { return `${this.slice(0, 1).toUpperCase()}${this.slice(1)}`; } } var s = new Str('asdf'); console.log(s.constructor);
The code above shows that the prototype chain is not configured as I expected. However, if I manually fix __proto__ using the code below, everything will work correctly.
'use strict'; class Str extends String { constructor(...args) { super(...args); Object.setPrototypeOf(this, new.target.prototype); } capitalize() { return `${this.slice(0, 1).toUpperCase()}${this.slice(1)}`; } } var s = new Str('asdf'); console.log(s.constructor);
I am very curious to find out why inheritance is not working as I expected.
source share