我一直在尝试使用Node5.3.0对ES2015中内置的String对象进行子类化。我正在使用一堆和谐标志运行未转移的代码。下面是完整的命令: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
考虑到规范明确指出字符串对象是可子类的(请参阅21.1.1 The String Constructor部分),我很难理解这是我做错了什么,还是Node中的bug,甚至是V8。
复制该问题的守则如下:
'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上面的代码演示了原型链没有像我预期的那样被设置。但是,如果我使用下面的代码手动修复__proto__,一切都会正常工作。
'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
我真的很想知道为什么继承不像我所期望的那样起作用。
发布于 2016-02-02 03:05:18
我还没有找到一个明确的答案,但我的快速和肮脏的解决方案一直有效,所以我将把它作为任何遇到同样问题的人的答案。
在从内置的字符串继承时,可以使用constructor()中的以下行修复原型链
Object.setPrototypeOf(this, new.target.prototype);
new.target.prototype位确保如果您进一步继承您自己的类型,原型链将继续正确。
https://stackoverflow.com/questions/34605185
复制相似问题