首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >未能将内置字符串对象子类

未能将内置字符串对象子类
EN

Stack Overflow用户
提问于 2016-01-05 06:04:44
回答 1查看 360关注 0票数 4

我一直在尝试使用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。

复制该问题的守则如下:

代码语言:javascript
复制
'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__,一切都会正常工作。

代码语言:javascript
复制
'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

我真的很想知道为什么继承不像我所期望的那样起作用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2016-02-02 03:05:18

我还没有找到一个明确的答案,但我的快速和肮脏的解决方案一直有效,所以我将把它作为任何遇到同样问题的人的答案。

在从内置的字符串继承时,可以使用constructor()中的以下行修复原型链

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

new.target.prototype位确保如果您进一步继承您自己的类型,原型链将继续正确。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/34605185

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档