es6 class以及构造函数(constructor)

es5中,生成实例对象经过构造函数来生成:javascript

function Fun(a,b) {
    this.a = a;
    this.b = b;
}
Fun.prototype.showA = function () {
    console.log(this.a)
}
var fun = new Fun(1,2);
fun.showA();//1

  

es6则引用了class的概念,使得更接近java、c++等语言,更加直观。如:java

class Fun {
    constructor(a,b){
        this.a = a;
        this.b = b;
    }
    showA() {
        console.log(this.a);
    }
}
var fun = new Fun(1,2);
fun.showA();//1

这两种写法是同样的,在es6中,class能够理解为一个语法糖,只是让这种写法更加直观。
要注意的是,es6中声明新的实例必需要用new声明。
其中constructor为类的默认方法,经过new的调用能够执行这个方法。每一个类都必需要有这个方法,若是没有显示定义,则一个空的constructor被添加到类里面。constructor方法默认返回实例对象,即this。也能够返回其余对象。这事,新的实例instanceof当前class就会报错。c++

相关文章
相关标签/搜索