构造函数
JavaScript 作为一个面向对象语言类和对象的定义和实现在其中体现了及其重要的作用,在ES6之前一般的定义构造函数的方法如下:
function Rect(width,height){
this.width=width
this.height=height
this.getArea=function(){
return this.width*this.height
}
}
const rect = new Rect(10, 10)
console.log(rect.getArea())//100
其使用函数绑定this的方式定义构造函数,用于描述类(Class)和对象不是这么的清楚,ES6提出Class的方法定义类
class Rect { }
const rect=new Rect()
ES6类的定义和方法
constructor
类使用constructor的方式定义构造器并初始化一个对象
class Rect {
constructor(width, height) {
this.width = width;
this.height = height
}
}
super
Class类使用 extends关键词实现继承,constructor 内部可以使用关键词 super 调用超类的相应方法
class Rect {
constructor(width, height) {
super();
this.width = width;
this.height = height
}
}
ES6 规定子类继承的子类constructor 中必须调用
super()
才能成功绑定子类的this(在使用this之前必须调用一次super()),但是super的作用并不单单是继承父类,如果是这样的话我觉得extends关键词就已经很好的体现了继承了,它的另一个重要的作用了调用父类的方法。
class Father{
a(){
console.log('我是父类的方法')
}
}
class son extends Father{
a(){
super.a()
}
}
const s=new son()
s.a()//我是父类的方法
静态方法
在方法前使用static定义静态方法,静态方法不能被实例继承,而是用类来直接调用。
class Rect{
static a(){
console.log('我是静态方法')
}
}
Rect.a()//我是静态方法
如果使用实例调用会抛出错误:
const s=new Rect()
s.a()//s.a is not a function
Class setter/getter修饰符使用方法
类实例化的时候会调用一次setter。也可以自己设置
class Getter {
//Getter
get a() {
console.log(this._a)
return '我是getter获取属性来的';
}
set a(a) {
console.log('setter')
this._a = a;//如果设置this.a=a 会无穷调用setter 方法
}
}
let son=new Getter()
son.a=4
console.log(son.a)
使用extends创建子类(继承)
普通函数的继承与创建子类可以看我另外一篇文章:
https://blog.csdn.net/qq_36754767/article/details/89643221
extends用于创建一个类的子类
class Father{
constructor(name){
this.name=name
}
}
class Child extends Father{
slg(){
console.log(this.name+' speak')
}
}
const son=new Child('forcehack')
son.slg()//forcehack speak
如果子类存在构造函数,想要调用父类,在使用this之前需要调用super()
也可扩展基于函数的类
function Father(name){
this.name=name
}
class Child extends Father{
slg(){
console.log(this.name+' speak')
}
}
const son=new Child('forcehack')
son.slg()//forcehack speak