跳到主要內容

@babel/plugin-transform-private-property-in-object

資訊

此外掛程式包含在 @babel/preset-env 中,在 ES2022

範例

JavaScript
class Foo {
#bar = "bar";

test(obj) {
return #bar in obj;
}
}

輸出

JavaScript
class Foo {
constructor() {
_bar.set(this, {
writable: true,
value: "bar",
});
}

test() {
return _bar.has(this);
}
}

var _bar = new WeakMap();

安裝

npm install --save-dev @babel/plugin-transform-private-property-in-object

用法

babel.config.json
{
"plugins": ["@babel/plugin-transform-private-property-in-object"]
}

透過 CLI

Shell
babel --plugins @babel/plugin-transform-private-property-in-object

透過 Node API

JavaScript
require("@babel/core").transformSync("code", {
plugins: ["@babel/plugin-transform-private-property-in-object"],
});

選項

loose

布林值,預設為 false

備註

loose 模式組態設定必須@babel/transform-class-properties 相同。

當為 true 時,私有屬性 in 表達式會在物件上檢查自己的屬性(而非繼承的屬性),而不是檢查 WeakSet 內部是否存在。這會提升效能和除錯(一般屬性存取與 .get())的代價,但可能會透過 Object.getOwnPropertyNames 等方式洩漏「私有」屬性。

警告

考慮移轉到頂層 privateFieldsAsProperties 假設。

babel.config.json
{
"assumptions": {
"privateFieldsAsProperties": true,
"setPublicClassFields": true
}
}

請注意,privateFieldsAsPropertiessetPublicClassFields 都必須設為 true

範例

JavaScript
class Foo {
#bar = "bar";

test(obj) {
return #bar in obj;
}
}

輸出

JavaScript
class Foo {
constructor() {
Object.defineProperty(this, _bar, {
writable: true,
value: "bar",
});
}

test() {
return Object.prototype.hasOwnProperty.call(this, _bar);
}
}

var _bar = babelHelpers.classPrivateFieldLooseKey("bar");
提示

您可以在 這裡 閱讀更多有關配置外掛選項的資訊

參考文獻