类的定义
类实际上就是es5构造函数的语法糖,简化了声明构造函数、原型方法以及实现继承的过程
类的特点
1.通过new操作符来创建一个实例对象,但不能把类当做普通函数去调用
2.在类的头部可以定义实例属性
3.在类的内部可以声明constructor表示构造方法,也可以自定义一些方法作为原型方法
4.使用static关键字,标识静态属性和静态方法
5.使用get和set关键字定义属性,拦截属性的读取和设置行为(本质是实例属性)
class Animal {
static type = 'animal';
static getType() {
return this.type;
}
age = 1;
get speak() {
return 'I am ' + this.age;
}
set speak(value) {
this.age = value;
}
constructor(name) {
this.name = name;
}
run() {
console.log(this.name + ' is running');
}
}
const bird = new Animal('bird');
console.log(Animal.getType()); // animal
console.log(bird.speak); // I am 1
bird.speak = 2;
console.log(bird.speak); // I am 2
bird.run(); // bird is running
6.可以使用extends和super关键字进行继承
// 父类
class Animal {
constructor(type, name) {
this.name = name;
this.getType = function () {
return type;
};
}
print() {
console.log(this.name, 111);
}
}
// 子类继承父类原型方法
class Dog extends Animal {
constructor(name) {
// 子类继承父类实例方法和属性
super('dog', name);
}
}
const dog = new Dog('小黑', 2, 'boy');
console.log(dog); // { name: '小黑', getType: function () {return type; } }
console.log(dog.getType()); // dog
console.log(dog.print()); // 小黑
实现继承的原理
实际就是将class写法转成es5的写法:
// 父类定义实例方法和属性
function Animal(type, name) {
this.name = name;
this.getType = function() {
return type;
};
}
// 父类定义原型方法
Animal.prototype.print = function() {
console.log(this.name, 111);
};
// 子类继承父类实例方法和属性
function Dog(name) {
Animal.call(this, 'dog', name);
}
// 子类继承父类的原型方法
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
// 创建实例
var dog = new Dog('小黑');
console.log(dog); // { name: '小黑', getType: function () {return 'dog'; }, print: function(){} }
console.log(dog.getType()); // dog
dog.print(); // 小黑 111
浙公网安备 33010602011771号