下列是一个具有四个类属性的类,它将被转译。
class Bork {
// 设置属性初始值语法
instanceProperty = "bork";
boundFunction = () => {
return this.instanceProperty;
}
// 静态类属性
static staticProperty = "babelIsCool";
static staticFunction = function() {
return Bork.staticProperty;
}
}
let myBork = new Bork;
// 设置的属性初始值不在原型上
console.log(myBork.__proto__.boundFunction); // > undefined
// 绑定 Bound 函数到类实例
console.log(myBork.boundFunction.call(undefined)); // > "bork"
// 该类拥有静态函数
console.log(Bork.staticFunction()); // > "babelIsCool"
npm install --save-dev babel-plugin-transform-class-properties
.babelrc
(推荐).babelrc
// 未包含选项
{
"plugins": ["transform-class-properties"]
}
// 包含选项
{
"plugins": [
["transform-class-properties", { "spec": true }]
]
}
babel --plugins transform-class-properties script.js
require("babel-core").transform("code", {
plugins: ["transform-class-properties"]
});
spec
boolean
,默认为 false
。
类属性使用 Object.definePropertyClass
进行编译。即使没有初始化静态字段也是如此。