类的基本使用
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
// 构造函数的方式
function Person(name, age)
{
this.name = name;
this.age = age;
}
var person = new Person('Peter', 30);
console.log(person);
// 类的方式
class Student
{
// 构造方法
constructor(name, age)
{
this.name = name;
this.age = age;
}
}
var student = new Student('Tom', 18);
console.log(student);
</script>
</body>
</html>
类中的方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
// 构造函数的方式
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
{
// 构造方法
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>
类的静态方法
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
class Student
{
// 构造方法
constructor(name, age)
{
this.name = name;
this.age = age;
}
static say() {
console.log('Hellow');
}
}
// 只能通过类本身访问
Student.say();
</script>
</body>
</html>
类的继承
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<script type="text/javascript">
class Person
{
// 构造方法
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
{
// 构造方法
constructor(name, age, gender)
{
// 必须调用父类构造方法,否则会报错
super(name, age);
this.gender = gender;
}
// 重写父类 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>
网友评论