在 JavaScript 中創(chuàng)建私有成員

面向?qū)ο缶幊陶Z(yǔ)言中的 private 關(guān)鍵字是一個(gè)訪問(wèn)修飾符,可用于使屬性和方法只能在聲明的類中訪問(wèn)。這使得隱藏底層邏輯變得容易,這些底層邏輯應(yīng)該被隱藏起來(lái),并且不應(yīng)該與類的外部交互。
但是如何在 JavaScript 中實(shí)現(xiàn)類似的功能呢? 沒(méi)有保留關(guān)鍵字 private ,但在新的標(biāo)準(zhǔn)中 JavaScript 有自己的方法來(lái)創(chuàng)建類私有成員,但目前還處于 ES2020 試驗(yàn)草案中,并且語(yǔ)法比較奇怪,以 # 作為前綴。下面介紹幾種在 JavaScript 代碼中實(shí)現(xiàn)私有屬性和方法的方式。
使用閉包
使用閉包可以使用私有屬性或者方法的封裝。利用閉包可以訪問(wèn)外部函數(shù)的變量特征。如下代碼片段:
function MyProfile() {
const myTitle = "DevPoint";
return {
getTitle: function () {
return myTitle;
},
};
}
const myProfile = MyProfile();
console.log(myProfile.getTitle()); // DevPoint
這可以轉(zhuǎn)化為將最頂層的自調(diào)用函數(shù)調(diào)用分配給一個(gè)變量,并且只用函數(shù)返回來(lái)公開(kāi)它的一些內(nèi)部函數(shù):
const ButtonCreator = (function () {
const properties = {
width: 100,
height: 50,
};
const getWidth = () => properties.width;
const getHeight = () => properties.height;
const setWidth = (width) => (properties.width = width);
const setHeight = (height) => (properties.height = height);
return function (width, height) {
properties.width = width;
properties.height = height;
return {
getWidth,
getHeight,
setWidth,
setHeight,
};
};
})();
const button = new ButtonCreator(600, 360);
console.log(button.getHeight()); // 360
使用 ES6 類
為了使代碼更類似于 OOP 方法,可以使用 ES6 中引入的 class 關(guān)鍵字。要使屬性和方法私有,可以在類之外定義它們。就對(duì)上面的 ButtonCreator 的例子使用 class 進(jìn)行重構(gòu):
const properties = {
width: 100,
height: 50,
};
class ButtonCreator {
constructor(width, height) {
properties.width = width;
properties.height = height;
}
getWidth = () => properties.width;
getHeight = () => properties.height;
setWidth = (width) => (properties.width = width);
setHeight = (height) => (properties.height = height);
}
const button = new ButtonCreator(600, 360);
console.log(button.getHeight()); // 360
現(xiàn)在假設(shè)屬性是公共的,但想在私有方法中使用它們,其中上下文指向 ButtonCreator,可以通過(guò)以下方式實(shí)現(xiàn)它:
const privates = {
calculateWidth() {
return this.width;
},
};
class ButtonCreator {
constructor(width, height) {
this.width = width;
this.height = height;
}
getWidth = () => privates.calculateWidth.call(this);
getHeight = () => this.height;
setWidth = (width) => (this.width = width);
setHeight = (height) => (this.height = height);
}
const button = new ButtonCreator(600, 360);
console.log(button.getHeight()); // 360
上面的代碼使用了 Function.prototype.call,它用于調(diào)用具有給定上下文的函數(shù)。在例子中,使用 ButtonCreator 類的上下文。如果私有函數(shù)也需要參數(shù),可以將它們作為附加參數(shù)傳遞以調(diào)用:
const privates = {
calculateWidth(percent) {
return this.width * percent;
},
};
class ButtonCreator {
constructor(width, height) {
this.width = width;
this.height = height;
}
getWidth = () => privates.calculateWidth.call(this, 0.1);
getHeight = () => this.height;
setWidth = (width) => (this.width = width);
setHeight = (height) => (this.height = height);
}
const button = new ButtonCreator(600, 360);
console.log(button.getWidth()); // 60
使用 ES2020 提案
還處于 ES2020 試驗(yàn)草案中,引入了私有方法或者屬性的定義,語(yǔ)法比較奇怪,以 # 作為前綴。
class ButtonCreator {
#width;
#height;
constructor(width, height) {
this.#width = width;
this.#height = height;
}
// 私有方法
#calculateWidth() {
return this.#width;
}
getWidth = () => this.#calculateWidth();
getHeight = () => this.#height;
setWidth = (width) => (this.#width = width);
setHeight = (height) => (this.#height = height);
}
const button = new ButtonCreator(600, 360);
console.log(button.width); // undefined
console.log(button.getWidth()); // 600
使用 WeakMap
這種方法建立在閉包方法之上,使用作用域變量方法創(chuàng)建一個(gè)私有 WeakMap,然后使用該 WeakMap 檢索與此相關(guān)的私有數(shù)據(jù)。這比作用域變量方法更快,因?yàn)樗袑?shí)例都可以共享一個(gè) WeakMap,所以不需要每次創(chuàng)建實(shí)例時(shí)都重新創(chuàng)建方法。
const ButtonCreator = (function () {
const privateProps = new WeakMap();
class ButtonCreator {
constructor(width, height, name) {
this.name = name; // 公共屬性
privateProps.set(this, {
width, // 私有屬性
height, // 私有屬性
calculateWidth: () => privateProps.get(this).width, // 私有方法
});
}
getWidth = () => privateProps.get(this).calculateWidth();
getHeight = () => privateProps.get(this).height;
}
return ButtonCreator;
})();
const button = new ButtonCreator(600, 360);
console.log(button.width); // undefined
console.log(button.getWidth()); // 600
這種方式對(duì)于私有方法的使用有點(diǎn)別扭。
使用 TypeScript
可以將 TypeScript 用作 JavaScript 的一種風(fēng)格,可以使用 private 關(guān)鍵字從面向?qū)ο蟮恼Z(yǔ)言中真正重新創(chuàng)建功能。
class ButtonCreator {
private width: number;
private height: number;
constructor(width: number, height: number) {
this.width = width;
this.height = height;
}
private calculateWidth() {
return this.width;
}
public getWidth() {
return this.calculateWidth();
}
public getHeight() {
return this.height;
}
}
const button = new ButtonCreator(600, 360);
console.log(button.getWidth()); // 600
console.log(button.width); // error TS2341: Property 'width' is private and only accessible within class 'ButtonCreator'.
總結(jié)
本文總結(jié)了再 JavaScript 創(chuàng)建私有屬性的幾種方法,看個(gè)人喜歡。