原文地址:https://dev.to/bhagatparwinder/classes-in-javascript-basics-10ip
介绍
JavaScript 开发者有多种多样的代码风格,有的是函数式、有的是面向对象式。类或者类的构造器是面向对象编程的一部分。类可以看成创建对象的模板,这个模板可以设置一些初始值和提供一些特定的方法。
JavaScript 通过构造函数和 new 操作符完全可以提供这种模板,这也是多数人把 JavaScript 中的类作为一个语法糖。这并不完全正确,随着我们在这个JavaScript博客系列中的进展,你会发现这一点。
类或类关键字是在 ES2015/ES6 中引入的。
语法
class EmployeeRecord {
name = "New User";
id = 0;
constructor(firstName, lastName, id) {
this.name = `${firstName} ${lastName}`;
this.id = id;
}
}
const employee1 = new EmployeeRecord("Parwinder", "Bhagat", 1);
const employee2 = new EmployeeRecord("Lauren", "L", 2);
console.log(employee1.name); // Parwinder Bhagat
console.log(employee2.name); // Lauren L
类的声明是通过 class
关键字,然后跟着一个名字。类体是包含在大括号中的,除了缺少参数就像函数声明一样。
参数是被传到构造器中的,当类被实例化时用来初始化值。把它想象为类中的一个方法,同时一旦类创建了一个新对象它就会立马执行。在类中只有一个唯一的 “constructor” 方法。
类表达式
若类能被声明,那它们是否也得有表达式方式?这些表达式可以被命名也可以不命名。多数开发者使用类的声明语法。
let EmployeeRecord = class {
name = "New User";
id = 0;
constructor(firstName, lastName, id) {
this.name = `${firstName} ${lastName}`;
this.id = id;
}
}
const employee1 = new EmployeeRecord("Parwinder", "Bhagat", 1);
const employee2 = new EmployeeRecord("Lauren", "L", 2);
console.log(employee1.name); // Parwinder Bhagat
console.log(employee2.name); // Lauren L
Getters 和 Setters
我们通过对象的 getters 和 setters 来获取或设置属性的值,我们依旧可以在类中这样使用。
let EmployeeRecord = class {
firstName = "";
lastName = "";
constructor(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
get employeeFullName() {
return `${this.firstName} ${this.lastName}`;;
}
set employeeFirstName(firstName) {
this.firstName = firstName;
}
set employeeLastName(lastName) {
this.lastName = lastName;
}
}
const employee1 = new EmployeeRecord("Parwinder", "Bhagat");
const employee2 = new EmployeeRecord("Lauren", "L");
// With a getter you do not need the () brackets
console.log(employee1.employeeFullName);
console.log(employee2.employeeFullName);
// A setter will prohibit someone from outside the class from changing the setter
employee1.employeeFullName = "Ricky Ricardo"; // Cannot assign to 'employeeFullName' because it is a read-only property.
// But we can use our helpful setter to do so!
// Keep in mind that a setter only takes one value
employee1.employeeFirstName = "Ricky";
employee1.employeeLastName = "Ricardo";
console.log(employee1.employeeFullName); // Ricky Ricardo
这就是今天要讲解的内容!关注下一篇博文,我们将讨论类如何不仅仅是语法糖,以及它们与函数有什么不同。