1.class
JavaScript 语言中,生成实例对象的传统方法是通过构造函数。 ES6 提供了更接近传统语言的写法,引入了 Class(类)这个概念,作为对象的模板。通过class关键字,可以定义类。基本上,ES6 的class可以看作只是一个语法糖,它的绝大部分功能,ES5 都可以做到,新的class写法只是让对象原型的写法更加清晰更像面向对象编程的语法而已。所以ES6 的类,完全可以看作构造函数的另一种写法。
语法糖:具有特殊功能的代码写法,内部封装了一些方法,让一些复杂代码的编写及其用法变得简单使用
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
sayName(){
console.log("i am ",this.name);
}
}
2.构造函数
constructor方法是类的默认方法,通过new命令生成对象实例时,自动调用该方法。一个类必须有constructor方法,如果没有显式定义,一个空的constructor方法会被默认添加。
class Person{
}
等同于
class Person{
constructor(){}
}
3.实例方法
定义在类体中的方法称为实例方法。如下,sayName方法就是实例方法,本质上该方法应该是声明在Person.prototype中,可供所有的实例调用,因此称为实例方法。
class Person{
constructor(name,age){
this.name = name;
this.age = age;
}
sayName(){
console.log("i am ",this.name);
}
}
4.静态方法
通过static关键字来定义静态属性和静态方法。静态属性和静态方法是定义在类【构造函数】上的,所以可以通过类【构造函数】直接访问。在静态方法中,this指向当前类【构造函数】
class Person{
static num = 200;
static number(){
return this.num;
}
}
console.log(Person.number()); //200
5.继承
class 可以通过extends关键字实现继承,这比 ES5 的通过修改原型链实现继承,要简洁很多。子类中可以没有构造函数,系统会默认提供一个。子类如果提供了构造函数就必须显示调用super。super函数类似于之前的借用构造函数。
class Animal {
constructor(name){
this.name = name;
}
sayName(){
console.log(“my name is ”,this.name);
}
}
class Dog extends Animal{
constructor(name,age){
super(name); this.age = age;
}
}
class Person {
// 静态属性
static gender = 'male'
// 构造器
constructor(name, age) {
// 实例属性
this.name = name
this.age = age
}
// 静态方法
static sayGender () {
console.log(this.gender);
}
// 实例方法(存在构造函数的原型对象中)
sayName () {
console.log(this.name);
}
}
// 实例化
let p = new Person('张三', 12)
// p.sayName()
// console.log(p);
// 静态方法属性调用
console.log(Person.gender);
Person.sayGender()
class Animal {
// 静态属性
static animalColor = 'white'
constructor(name, age) {
this.name = name
this.age = age
console.log('Animal构造器');
}
// 静态方法
static animalFun () {
console.log('Animal的静态方法');
}
// 实例方法
animalFun () {
console.log('Animal的实例方法');
}
}
class Dog extends Animal {
constructor(name, age, weight) {
super(name, age)
this.weight = weight
console.log('Dog的构造器');
}
}
// 实例方法属性的继承
// 子类原型对象继承父类原型对象
let dog = new Dog('金毛', 1, 30);
console.log(dog);
dog.animalFun()
console.log(dog.__proto__.__proto__ === Animal.prototype);
// 静态方法属性的继承
// 子类的构造函数继承父类的构造函数
// 子类构造函数的原型对象指向父类构造函数
// console.log(Dog.animalColor);
// Dog.animalFun();
// console.log(Dog.__proto__ === Animal);