类是构造函数的语法糖
(1) es5构造函数
function Animal(name,age){
this.name = name;
this.age = age;
}
Animal.prototype.sayName = function(){
console.log("my name is",this.name);
}
Animal.prototype.sayAge = function(){
console.log("my age is",this.age);
}
//继承
function Dog(name,age,gender){
Animal.call(this,name,age)
this.gender = gender;
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
Dog.prototype.sayGender = function(){
console.log("my gender is",this.gender);
}
let d = new Dog("一休",2,"male");
d.sayName()
d.sayGender();
(2) 语法
1、 类的声明
class 类名 {
constructor(构造函数形式参数){
this.xxx = xxx;
}
xxx(){
}
yyy(){
}
}
this表示当前构造函数的实例对象
- 类的继承
class 子类名 extends 父类名 {
constuctor(子构造函数形式参数){
super(x,y)
this.z = z;
}
}
任意一个类如果你不提供构造函数,那么系统会为你自动分配一个构造函数,这个构造函数如下
constructor(a,b,c){
super(a)
}
super 是借用构造函数的语法糖
(3) this
不管是构造函数还是普通方法,this都指向当前类的实例对象
es6的类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>es6 类</title>
<script>
// Animal类
class Animal {
//1. 构造方法
constructor(name,age){
this.name = name;
this.age = age;
}
//2. 普通方法
sayName(){
console.log("我的名字叫",this.name);
}
sayAge(){
console.log("我的年龄为",this.age)
}
}
// 原型链继承
class Dog extends Animal{
constructor(name,age,gender){
super(name,age);
this.gender = gender;
}
sayGender(){
console.log("我的性别",this.gender);
}
}
let d = new Dog("一休",2,"male");
console.log(d);
d.sayName();
d.sayGender();
</script>
</head>
<body>
</body>
</html>