類(lèi)的基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
// 構(gòu)造函數(shù)的方式
function Person(name, age)
{
this.name = name;
this.age = age;
}
var person = new Person('Peter', 30);
console.log(person);
// 類(lèi)的方式
class Student
{
// 構(gòu)造方法
constructor(name, age)
{
this.name = name;
this.age = age;
}
}
var student = new Student('Tom', 18);
console.log(student);
</script>
</body>
</html>
類(lèi)中的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
// 構(gòu)造函數(shù)的方式
function Person(name, age)
{
this.name = name;
this.age = age;
}
Person.prototype.say = function() {
console.log(`I am ${this.name}, I am ${this.age}`);
}
var person = new Person('Peter', 30);
person.say();
// class 形式
class Student
{
// 構(gòu)造方法
constructor(name, age)
{
this.name = name;
this.age = age;
}
say() {
console.log(`I am ${this.name}, I am ${this.age}`);
}
}
var student = new Student('Tom', 18);
student.say();
</script>
</body>
</html>
類(lèi)的靜態(tài)方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
class Student
{
// 構(gòu)造方法
constructor(name, age)
{
this.name = name;
this.age = age;
}
static say() {
console.log('Hellow');
}
}
// 只能通過(guò)類(lèi)本身訪(fǎng)問(wèn)
Student.say();
</script>
</body>
</html>
類(lèi)的繼承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
class Person
{
// 構(gòu)造方法
constructor(name, age)
{
this.name = name;
this.age = age;
}
say() {
console.log(`I am ${this.name}, I am ${this.age}`);
}
}
class Student extends Person
{
}
class Teacher extends Person
{
// 構(gòu)造方法
constructor(name, age, gender)
{
// 必須調(diào)用父類(lèi)構(gòu)造方法,否則會(huì)報(bào)錯(cuò)
super(name, age);
this.gender = gender;
}
// 重寫(xiě)父類(lèi) Person 的 say 方法
say() {
console.log(`I am ${this.name}, I am ${this.age}, I am a teacher`);
}
}
var student = new Student('Tom', 18);
student.say();
var teacher = new Teacher('Peter', 30, '男');
teacher.say();
</script>
</body>
</html>