我一直在尝试使用 Node 5.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
鉴于规范明确规定 String 对象是可子类化的(请参阅部分21.1.1 The String Constructor
),我很难理解这是否是我做错的事情,或者是 Node 甚至 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
我真的很想知道为什么继承没有按我的预期工作。
我还没有找到这个问题的明确答案,但我的快速而肮脏的解决方案目前已经有效,所以我将把它作为任何遇到同样问题的人的答案。
您可以在从内置 String 继承时使用以下行来修复原型链:constructor()
:
Object.setPrototypeOf(this, new.target.prototype);
The new.target.prototype
确保如果您进一步从自己的类型继承,原型链将继续正确。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)