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);
相關文章
相關標籤/搜索