ES6之前通过 构造函数+原型 实现面向对象编程,ES6通过 类实现面向对象编程
构造函数:
(1) 构造函数有原型对象prototype
(2) 构造函数原型对象prototype 里面有constructor 指向构造函数本身
(3) 构造函数可以通过原型对象添加方法
(4) 构造函数创建的实例对象有__proto__ 原型指向 构造函数的原型对象
类的本质:
- 类的本质是一个函数,也可以简单的认为类是构造函数的另一种写法。
- 类的所有方法都定义在类的prototype属性上
- 类创建的实例,里面也有__proto__ 指向类的prototype原型对象
- ES6的类的绝大部分功能,ES5都可以做到,新的class写法只是让对象原型的写法更加清晰、更像面向对象编程的语法而已。所以ES6的类其实就是语法糖。
1. 创建对象:
class Star{
//class body
}
2. 创建实例:
var xx = new Star();
3. 类constructor构造函数
constructor()方法是类的构造函数,接收传递过来的参数,返回实例对象。
new生成对象实例时自动调用该方法,若无显示定义,类内部会自动创建一个constructor()。
[注]类里函数不需要写function,多个方法之间不需要逗号分隔
4. 继承
语法:
class Father {
constructor(x, y) {
this.x = x;
this.y = y;
}
sum() {
console.log(this.x + this.y);
}
}
class Son extends Father {
constructor(x, y) {
super(x, y); //调用父类中的构造函数,super:实现子类的参数传递给父类
}
}
let son = new Son(1,2);
son.sum();
Super关键字:
- 用于访问和调用对象父类上的函数。可以调用父类的构造函数,也可以调用父类的普通函数(super.函数名())
- 子类在构造函数中使用super, 必须放到 this 前面 (必须先调用父类的构造方法,在使用子类构造方法
5. 注意点:
- 在 ES6 中类没有变量提升,所以必须先定义类,才能通过类实例化对象.
- 类里面的共有属性和方法一定要加this使用.
- 类里面的this指向问题:
constructor 里面的this指向实例对象, 方法里面的this 指向这个方法的调用者
var that;
var _that;
class Star {
constructor(uname, age) {
// constructor 里面的this 指向的是 创建的实例对象
that = this;
console.log(this);
this.uname = uname;
this.age = age;
// this.sing();
this.btn = document.querySelector('button');
this.btn.onclick = this.sing;
}
sing() {
// 这个sing方法里面的this 指向的是 btn 这个按钮,因为这个按钮调用了这个函数
console.log(this);
//console.log(this . uname); undefined
console.log(that.uname); // that里面存储的是constructor里面的this
}
dance() {
// 这个dance里面的this 指向的是实例对象 ldh 因为ldh 调用了这个函数
_that = this;
console.log(this);
}
}
var ldh = new Star('刘德华');
console.log(that === ldh);
ldh.dance();
console.log(_that === ldh);