@babel/plugin-proposal-class-properties
一种类的properties的另外一种书写方法,这里的class properties指的是类的实例方法或者实例属性、类的静态方法或者静态属性。特别注意,如果class properties 前面没有添加static,是将属性或者方法添加实例对象上,加上static,是表示类的静态方法或者属性。
class Bork {
//Property initializer syntax
instanceProperty = "bork";
boundFunction = () => {
return this.instanceProperty;
};
//Static class properties
static staticProperty = "babelIsCool";
static staticFunction = function() {
return Bork.staticProperty;
};
}
let myBork = new Bork;
//Property initializers are not on the prototype.
console.log(myBork.__proto__.boundFunction); // > undefined
//Bound functions are bound to the class instance.
console.log(myBork.boundFunction.call(undefined)); // > "bork"
//Static function exists on the class.
console.log(Bork.staticFunction()); // > "babelIsCool"
安装
npm install --save-dev @babel/plugin-proposal-class-properties
用法(.babelrc或者其它)
{
"plugins": ["@babel/plugin-proposal-class-properties"]
}
带有选项设置:
{
"plugins": [
["@babel/plugin-proposal-class-properties", { "loose": true }]
]
}
options
loose:boolean,默认为false
当loose设置为true,代码被以赋值表达式的形式编译,否则,代码以Object.defineProperty来编译。
比如:
class Bork {
static a = 'foo';
static b;
x = 'bar';
y;
}
如果没有设置loose,或者设置loose为false,则将以Object.defineProperty形式编译:
var Bork = function Bork() {
babelHelpers.classCallCheck(this, Bork);
Object.defineProperty(this, "x", {
configurable: true,
enumerable: true,
writable: true,
value: 'bar'
});
Object.defineProperty(this, "y", {
configurable: true,
enumerable: true,
writable: true,
value: void 0
});
};
Object.defineProperty(Bork, "a", {
configurable: true,
enumerable: true,
writable: true,
value: 'foo'
});
Object.defineProperty(Bork, "b", {
configurable: true,
enumerable: true,
writable: true,
value: void 0
});
如果设置了loose为true,则将会以赋值表达式模式编译:
var Bork = function Bork() {
babelHelpers.classCallCheck(this, Bork);
this.x = 'bar';
this.y = void 0;
};
Bork.a = 'foo';
Bork.b = void 0;