目录
# class 第一个好:私有变量
如果不用 class , 还有什么更优雅的方法实现以下子类的私有变量吗?
class Person {
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
} // Person.constructor
get FullName() {
return this.firstName + ' ' + this.lastName;
}
} // Person
class Employee extends Person {
#salary;
constructor(firstName, lastName, salary) {
super(firstName, lastName);
this.salary = salary;
}
get salary() {
return this.#salary;
}
set salary(salary) {
this.#salary = salary;
console.log('Salary changed for ' + this.fullName + ' : $' + this.salary);
}
} // Employee
已复制
设想下,我们用原型链的思路模拟(对象):
const Person = {
set givenName(givenName) {
this._givenName = givenName;
},
set familyName(familyName) {
this._familyName = familyName;
},
get fullName() {
return `${this._givenName} ${this._familyName}`;
},
};
const test = Person; // 这里假设用 对象 模拟 类
test.givenName = 'Joe';
test.familyName = 'Martinez';
console.log('test.fullName', test.fullName); // Joe Martinez
console.log('test.givenName', test.givenName); // undefined
console.log('test._givenName', test._givenName); // Joe
已复制
没有实现私有属性 _givenName
而 class 可以将值存为私有,使得对象外部不能修改:
代码示例可参考:javascript-classes-are-not-just-syntactic-sugar (opens new window)
# class 第二个好:super 继承
class 可以通过 super 更优雅的实现继承、和重写,比如:
class Cash {
constructor() {
this.total = 0;
}
add(amount) {
this.total += amount;
if (this.total < 0) this.total = 0;
}
} // Cash
class Nickles extends Cash {
add(amount) {
super.add(amount * 5);
}
} // Nickles
已复制
如果是按照老样子,原型链,它可能是这样的:
const Cash = function() {
this.total = 0;
}; // Cash
Cash.prototype = {
add: function(amount) {
this.total += amount;
if (this.total < 0) this.total = 0;
},
}; // Cash.prototype
const Nickles = function() {
Object.assign(this, new Cash());
this.add = function(amount) {
Cash.add.apply(this, amount);
};
}; // Nickles
已复制
读起来有点乱,this 指来指去,还有在构造函数中手动做的 assign 操作,这会增加代码执行耗时。
# 总结
综上两点,JS class 还是非常有使用它的价值的,不用逃避,把它用在合适的场景,肯定会发现其魅力~~
