Error constructing a subclass of String object

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); //[Function: String] console.log(s.__proto__) //[String: ''] console.log(s.capitalize()); //TypeError: s.capitalize is not a function 

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); //[Function: Str] console.log(s.__proto__); //Str {} console.log(s.capitalize()); //Asdf 

I am very curious to find out why inheritance is not working as I expected.

+4
source share
1 answer

I have yet to find a final answer to this question, but my quick and dirty solution is working at the moment, so I will leave it the answer for those who are facing the same problem.

You can fix the prototype chain when inheriting from the inline String using the following line in constructor() :

Object.setPrototypeOf(this, new.target.prototype);

The new.target.prototype bit ensures that if you inherit further from your own type, the prototype chain will remain valid.

+1
source

All Articles