1、类字段声明
在 ES13 之前,类字段只能在构造函数中声明,与许多其他语言不同,我们不能在类的最外层范围内声明或定义它们。
//创建类class
class Star { //类名我们还是习惯性的定义首字母大写
str = '123'
constructor(name, age) { //创建类名后面不要加小括号 生成实例类名后面加小括号
this.name1 = name//构造函数不需要加function
this.age1 = age
this.str = 1234445
this.sing()
}
sing(song) { //多个函数在类中不要用逗号分开
// console.log(ldh.name1+song);
console.log(this.name1);
}
}
// 利用类创建对象 new
var ldh = new Star('刘德华', 18) //constructor函数只要new生成实例就会自动调用这个函数
console.log(ldh.str);
ES13 消除了这个限制,现在我们可以编写如下代码:
class Star {
color = 'blue';
age = 2;
}
const car = new Star();
console.log( Star.color); // blue
console.log( Star.age); // 2
2、私有方法和字段
使用 ES13,我们现在可以将私有字段和成员添加到类中,方法是在其前面加上井号 (#),试图从类外部访问它们会导致错误
class Person {
#firstName = 'Joseph';
#lastName = 'Stevens';
get name() {
return `${this.#firstName} ${this.#lastName}`;
}
}
const person = new Person();
console.log(person.name); //Joseph Stevens
// SyntaxError: Private field '#firstName' must be
// declared in an enclosing class
// console.log(person.#firstName); 会报错
// console.log(person.#lastName);
3、静态类字段和静态私有方法
我们现在可以在 ES13 中为类声明静态字段和静态私有方法,静态方法可以使用 this 关键字访问类中的其他私有/公共静态成员,实例方法可以使用 this.constructor 访问它们。
class Person2 {
static #count = 0;
static getCount() {
return this.#count;
}
constructor() {
this.constructor.#incrementCount();
}
static #incrementCount() {
this.#count++;
}
}
const person1 = new Person2();
const person2 = new Person2();
console.log(Person2.getCount()); // 2
4、at() 方法进行索引
新的 at() 方法让我们可以更简洁、更有表现力地访问数组末尾的第 N 个元素,我们只需将负值 -N 传递给 at()。
const arr = ['a', 'b', 'c', 'd'];
console.log(arr.at(-1)); // d 获取数组倒数第一个
console.log(arr.at(-2)); // c 获取数组倒数第二个
console.log(arr.at(0)); // a 获取数组第一个
// 除了数组,字符串现在也有 at() 方法。
const str = 'Coding Beauty';
console.log(str.at(-1)); // y
console.log(str.at(-2)); // t