@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;