类是 ES6 版本的JavaScript中引入的函数之一。
JavaScript类类似于 Javascript构造函数,它只是一个语法糖。构造函数定义为:
// 构造函数
function Person () {
this.name = 'John',
this.age = 23
}
// 创建一个对象
const person1 = new Person();
不用function
关键字,而是使用class
关键字来创建JS类。例如,
// 创建一个类
class Person {
constructor(name) {
this.name = name;
}
}
class
关键字用于创建一个类。这些属性是在构造函数中分配的。
现在您可以创建一个对象。例如,
// 创建一个类
class Person {
constructor(name) {
this.name = name;
}
}
// 创建一个对象
const person1 = new Person('John');
const person2 = new Person('Jack');
console.log(person1.name);//John
console.log(person2.name);//Jack
这里,person1
和person2Person
类的对象。
注意:每次创建对象时,都会自动调用类中的constructor()
方法。
使用构造函数时,将方法定义为:
// 构造函数
function Person (name) {
//将参数值分配给调用对象
this.name = name;
//定义方法
this.greet = function () {
return ('Hello'' + ' ' + this.name);
}
}
在JavaScript类中定义方法很容易。您只需提供方法的名称,后跟()
。例如,
class Person {
constructor(name) {
this.name = name;
}
//定义方法
greet() {
console.log(`Hello ${this.name}`);
}
}
let person1 = new Person('John');
// accessing property
console.log(person1.name);//John
// accessing method
person1.greet();//Hello John
注意:要访问对象的方法,您需要使用名称后跟()
的方法来调用该方法。
在JavaScript中,getter方法获取对象的值,而setter方法设置对象的值。
JavaScript类可能包括getter和setter 。您将get
关键字用于getter方法,将set
用于setter方法。例如,
class Person {
constructor(name) {
this.name = name;
}
//getter
get personName() {
return this.name;
}
//setter
set personName(x) {
this.name = x;
}
}
let person1 = new Person('Jack');
console.log(person1.name);//Jack
// 更改 name 属性的值
person1.personName = 'Sarah';
console.log(person1.name);//Sarah
使用前应定义一个类。与函数和其他JavaScript声明不同,该类不会提升。例如,
// 访问类
const p = new Person();//ReferenceError
// 定义类
class Person {
constructor(name) {
this.name = name;
}
}
如您所见,在定义类之前访问类会引发错误。
链接:https://www.learnfk.comhttps://www.learnfk.com/es6/classes.html
来源:LearnFk无涯教程网
类始终遵循'use-strict'。类中的所有代码都将自动进入严格模式。例如,
class Person {
constructor() {
a = 0;
this.name = a;
}
}
let p = new Person();//ReferenceError: Can't find variable: a
注意:JavaScript类是一种特殊的函数。并且 typeof
运算符为一个类返回 function
。
例如,
class Person {}
console.log(typeof Person);//function
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)