首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用BabelJS 6访问类的静态属性

使用BabelJS 6访问类的静态属性
EN

Stack Overflow用户
提问于 2015-11-28 00:34:38
回答 1查看 485关注 0票数 0

以下是演示该问题的最小应用程序:

代码语言:javascript
运行
复制
'use strict';

var _ = require('underscore');

class Model
{
    constructor(value) {
        this._value = value;
    }

    get value() {
        return this._value;
    }

    toJS() {
        return this.value;
    }
}

class ObjectModel extends Model
{
    static properties = {};

    constructor(value) {
        super(_.extend({}, new.target.properties, _.pick(value, _.keys(new.target.properties))));
    }
}

class PostModel extends ObjectModel
{
    static properties = {
        title: 'Hello'
        /* content: '<p>Lorem ipsum dolor sit amet</p>' */
    };
}

console.log(new PostModel({title: 'Nice day', aa: 11, bb: 22}).toJS());

它应该生成{title: 'Nice day'}。相反,它甚至不能编译。我明白了:

代码语言:javascript
运行
复制
$ babel app.js
SyntaxError: app.js: 'this' is not allowed before super()

我理解为什么要对对象属性执行此操作。但是我不能理解为什么对类变量也这样做。

在BabelJS 5中,我使用了这个技巧,完成了这项工作:

代码语言:javascript
运行
复制
class ObjectModel extends Model
{
    static properties = {};

    constructor(value) {
        if (0) { super(); }
        super(_.extend({}, this.constructor.properties, _.pick(value, _.keys(this.constructor.properties))));
    }
}

在版本6中,它可以编译,但在运行时会产生一个错误:

代码语言:javascript
运行
复制
Uncaught TypeError: Cannot read property 'constructor' of undefined

在调用super之前,有什么方法可以访问类的静态变量吗?使用像init()这样的东西而不是constructor是不可行的。也许创建自定义转换插件?

系统详细信息:

代码语言:javascript
运行
复制
$ babel --version
6.2.0 (babel-core 6.2.1)

$ cat .babelrc
{
    "presets": ["es2015", "stage-1"]
}

$ babel-doctor

Babel Doctor
Running sanity checks on your system. This may take a few minutes...

✔ Found config at /path/to/.babelrc
✔ No duplicate babel packages found
✔ All babel packages appear to be up to date
✔ You're on npm >=3.3.0

Everything looks all right!
EN

回答 1

Stack Overflow用户

发布于 2015-11-29 01:24:01

解决方案如下:

  1. 坚持使用@sjrd@loganfsmyth建议的new.target

类ObjectModel扩展模型{静态属性= {};构造函数(值){ super(_.extend({},new.target.properties,_.pick(value,_.keys(new.target.properties);}}

  • 创建一个转换器,将所有new.target (ES6)转换为this.constructor (ES5):

函数transpileNewTarget() { path.replaceWithSourceString('this.constructor');{transpileNewTarget:{ MetaProperty(path) { if (path.isMetaProperty() && path.node.meta.name == 'new‘&& path.node.property.name ==’==‘){ return };}

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

https://stackoverflow.com/questions/33961570

复制
相关文章

相似问题

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