ES6之类的其他书写方式
js
const methodName="sayHello";
class Person{
constructor(name, age, sex){
this.name = name;
//this.getAge();
//this.setAge();
this.age = age;
this.sex = sex;
}
get age(){
return this._age;
}
set age(age){
if(typeof age !== "number"){
throw new TypeError("age property must be a number");
}else if(age < 0){
age = 0;
}else if(age > 1000){
age = 1000;
}
this._age = age;
}
[methodName](){
console.log(this.name,this.age,this.sex)
}
}
const p1 = new Person("张三", 18, "男");
p1[methodName]()
这里是类的一些其他特点。
类的可计算成员名,和对象初始化的可计算属性类似,可以将成员名变成[]+表达式的形式。
getter和setter,在之前时期,我们可以使用函数的方式来进行 age 的读取和赋值的过程。但这种方式与属性的书写方式不一致,需要使用 p1.getAge() ,p1.setAge() 的方式。采用 getter 和 setter 可以直接写成属性的形式,p1.age , p1.age=10 。也可使用 Object.defineProperty 的方式书写。
静态成员是定义在构造函数的属性。无法通过实例对象访问。例如:
js
class Chess{
constructor(name){
this.name = name;
}
static width = 100;
static height = 100;
static show(){
console.log(this.name)
}
}
console.log(Chess.width, Chess.height)
Chess.show()
使用 static 关键字可以定义静态属性,可以通过 console.dir() 查看。
字段初始化器
js
class Test {
a=1;
b=2;
print=()=> {
console.log(this)
}
}
// function Test() {
// }
// Test.prototype.print=function(){
// console.log(this)
// }
const t1 = new Test();
const t2 = t1.print;
t2()
字段初始化器是指可以直接给成员赋值,这些成员会添加到构造器里。也可以赋值给一个方法,不过方法里的this指向存在问题。this会指向window,这时使用箭头函数可以使this永远绑定到对象上,虽然会造成一定的内存浪费。
类表达式,可以将类用在参数或返回值中。
js
const test=class{
print(){
console.log(this)
}
}
new test().print()