es6中的类及es5类的实现

目录es6

类的特色

1.类只能经过new获得

在es6中类的使用只能是经过new,若是你将它做为一个函数执行,将会报错。函数

//es6的写法
class  Child {
    constructor() {
        this.name  =  1;
    }
}
let  child  =  new  Child();
console.log(child.name)//1
//若是直接方法调用的形式,会报错
let  child  =  Child();//Class constructor Child cannot be invoked without 'new'

es5中的class其实就是一个方法,没有关键字classthis

//es5中类的写法,可是这样直接用方法名调用并不会报错
var  Person  = (function () {
    function  Person(name) {
        this.name  =  name;
    }
    Person.prototype.SayHello  =  function () {
        window.alert("My name is "  +  this.name  +  ".");
    };
    return  Person;
})();
var  p  =  Person()//不报错

为了实现相似于es6中的调用检查,咱们须要本身手写一个调用检查的函数。这个函数的原理就是用当前的this和构造函数进行比较,若是这个this指向的window,那么能够看出是用经过方法名直接调用的,若是this是构造函数那么就是经过new获得的es5

var  Person  = (function () {
//类的调用检测
    function  _classCheck(instance, constructor) {
        if (!(instance  instanceof  constructor)) {
            throw  new  Error('Class constructor Child cannot be invoked without new')
        }
    }
    function  Person(name) {
        this.name  =  name;
        _classCheck(this, Person)
    }
    Person.prototype.SayHello  =  function () {
        window.alert("My name is "  +  this.name  +  ".");
    };
    return  Person;
})();
var  p  =  Person()

子类会继承父类的公有属性和静态方法

es6中的写法prototype

//es6中的写法
class  Child  extends  Person {
    constructor() {
        super()
        this.name  =  1;
    }
}
//es5中的写法
var  Clild  = (function (Person) {
//类的调用检测
    function  _classCheck(instance, constructor) {
        if (!(instance  instanceof  constructor)) {
        throw  new  Error('Class constructor Child cannot be invoked without new')
        }
    }
//子类继承父类的方法
    function  _inherins(subclass, superclass) {
        subclass.prototype  =  Object.create(superclass.prototype, { constructor: { value:  subclass } })
        Object.setPrototypeOf(subclass, superclass)
    }
    _inherins(Clild, Person)
    function  Clild() {
        let obj=Person.call(this)//子类继承私有属性
        let that=this;
        if(typeof obj=='object'){
            that=obj
        }
        that.name=1;//解决了父类是引用类型的问题
        _classCheck(this, Clild)
        return that
    }
return  Clild;
})(Person);
相关文章
相关标签/搜索