序言
這篇文章主要講解面試中的一個(gè)問題 - ES6中的class語法的實(shí)現(xiàn)?
ECMAScript 6 實(shí)現(xiàn)了class,class是一個(gè)語法糖,使得js的編碼更清晰、更人性化、風(fēng)格更接近面向?qū)ο蟮母杏X;也使 IDE 、編譯期類型檢查器、代碼風(fēng)格檢查器等工具更方便地檢測代碼語法,做靜態(tài)分析。同樣的,這給沒有類就缺點(diǎn)什么的軟件開發(fā)工程師一個(gè)更低的門檻去接觸js。
ES6 class 的 ES5 代碼實(shí)現(xiàn)
JavaScript語言的傳統(tǒng)方法是通過構(gòu)造函數(shù)定義并生成新對象,這種寫法和傳統(tǒng)的面向?qū)ο笳Z言差異較大。所以,ES6引入了Class這個(gè)概念作為對象的模板。
constructor
效果:ES6創(chuàng)建一個(gè)class會(huì)默認(rèn)添加constructor方法,并在new調(diào)用時(shí)自動(dòng)調(diào)用該方法。
ES5:
function Person(name, age) { this.name = name; this.age = age;}Person.prototype.toString = function () { return '(' + this.name + ',' + this.age + ')';}var p = new Person('Mia', 18);console.log(p);// Person { name: 'Mia', age: 18 }ES6:
class Person { constructor(name, age) { this.name = name; this.age = age; } toString() { return '(' + this.name + ',' + this.age + ')'; }}var p = new Person('Mia', 18);console.log(p);// Person { name: 'Mia', age: 18 }ES6的class中constructor是構(gòu)造方法,對應(yīng)的是ES5中的構(gòu)造函數(shù)Person,this關(guān)鍵字則代表實(shí)例對象。
里面的class類可以看做是構(gòu)造函數(shù)的另一種寫法,由typeof Person === 'function'為true;Person === Person.prototype.constructor為true可以得出,類的數(shù)據(jù)類型就是函數(shù),類本身指向構(gòu)造函數(shù)。也可以說class的底層依然是function構(gòu)造函數(shù)。
類的公共方法都定義在類的prototype屬性上。可以使用Object.assign一次向類添加多個(gè)方法。
特別的:class的內(nèi)部定義的方法都是不可枚舉的(non-enumerable),這一點(diǎn)與ES5的行為不一致。
ES5:
Object.keys(Person.prototype); // ['toString']
ES6:
Object.keys(Person.prototype); // Person {}不可枚舉的代碼實(shí)現(xiàn)會(huì)在后面將ES6代碼用Babel轉(zhuǎn)碼之后解析。
new調(diào)用
效果:class類必須使用new調(diào)用,否則會(huì)報(bào)錯(cuò)。
ES5:
Person()// undefined
ES6:
Person() // TypeError: Class constructor Person cannot be invoked without 'new'
實(shí)例的屬性
效果:實(shí)例的屬性是顯式定義在this對象上,否則都是定義在原型上。類的所有實(shí)例共享一個(gè)原型對象,與ES5行為一致。
ES5:
function Person() { this.grade = { count: 0 };}ES6:
class Person { constructor() { this.grade = { count: 0 }; }}
新聞熱點(diǎn)
疑難解答
圖片精選