JavaScript 创建真正的私有方法有什么缺点
根据其他编程语言如C++,Java等,私有方法是指不能与其他类共享,不能直接通过对象访问的方法。这个规则也适用于JavaScript。
所以首先我们要看看如何使用JavaScript创建私有方法?主要有四个关键字可以在类中创建私有方法:
- var
- let
- const
- #(哈希)
示例:
Javascript
<script>
// class Geek
var Geek = function (article, published) {
// public member
this.programmingLang = "Js";
// private member
var topic = "private_method";
var status = published;
// private member function
var publish = () => {
console.log(article);
return status;
}
// calling private member
// function inside same class
console.log(publish());
};
// Geek1 is object of Geek class
var Geek1 = new Geek('ABC', 'YES');
// calling public member outside the class
console.log(Geek1.programmingLang);
<script/>
输出:
ABC
YES
Js
在JavaScript中创建真正的私有方法有两个主要的缺点。
- 无法在类外部调用私有方法。
- 当为同一个类创建不同的对象时,会产生内存效率问题,因为每个实例都会创建一个新的方法副本。
示例: 如果我们在类外部调用私有成员函数,那么会报错。
Javascript
<script>
var Geek = function (article, published) {
this.programmingLang = "Js";
var topic = "private_method";
var status = published;
var publish = () => {
console.log(article);
return status;
}
console.log(topic);
};
var Geek1 = new Geek('ABC', 'YES');
console.log(Geek1.programmingLang);
console.log(publish());
<script />
输出:
但是下面的例子会得到正确的输出:
Javascript
<script>
class A {
// Private field
#foo;
constructor(foo) {
this.#foo = "ABC";
}
#privateFun(prefix) {
return prefix + this.#foo;
}
publicFun() {
return this.#privateFun(">>");
}
}
let a = new A();
console.log(a.publicFun());
<script/>
输出:
>>ABC
示例: 如果我们为同一个类创建不同的对象,那么每个对象会为自己创建一个实例或者说复制该函数的实例。在这种情况下,会出现内存效率问题。
Javascript
<script>
var Employee = function (name, comp, sal) {
this.name = name;
this.company = comp;
this.salary = sal;
// Private method
var Sal_increase = () => {
this.salary = this.salary + 45000;
};
// Public method
this.dispalySal = () => {
Sal_increase();
console.log(this.salary);
};
};
const A = new Employee("A", "dream", 45000);
const B = new Employee("B", "young", 6000);
const C = new Employee("C", "inspire", 9000);
A.dispalySal()
B.dispalySal()
C.dispalySal()
</script>
输出:
90000
51000
54000
注意: 提到的代码可以在HTML或控制台中运行。