es6 class進階【一個將class轉(zhuǎn)原型對象的例子】

背景

class的出現(xiàn),讓js開發(fā)者告別了使用原型對象模仿面向?qū)ο笾械念惡皖惱^承時代。在前端開發(fā)中,使用到class的地方非常之多,所以掌握class的用法已經(jīng)必不可少了。

劃重點

JS 中并沒有一個真正的 class 原始類型, class 僅僅只是對原型對象運用語法糖(PS:什么是語法糖?就是不用寫原始方法,而是提供了一種簡單的寫法,底層還是原始的方法)。所以,只有理解如何使用原型對象實現(xiàn)類和類繼承,才能真正地用好 class?!娟P(guān)于使用原型對象實現(xiàn)類和類繼承詳解,后續(xù)持續(xù)更新】

來看一個class的例子

先記一個知識點:class里面可以寫 三種 方法,第一種是constructor內(nèi)部的方法,第二種是原型鏈上的方法,第三種是static函數(shù)靜態(tài)方法。

class Person{
  constructor(name) {
    this.name = name;
    // constructor內(nèi)部的方法,在 new 一個實例的時候就會生命這個方法,一般情況下也是在內(nèi)部調(diào)用的
    function hello1() {
      console.log(`hello1 ${name}, this is an inner function!`)
    }
    hello1()
  }
  hello2() {
    console.log(`hello2 ${this.name}, this is a prototype function!`);
  }
  // 靜態(tài)方法,不需要new就可以調(diào)用
  static hello3() {
    // 這里的 this.name 返回的是class的名字
    console.log(`hello3 ${this.name}, this is a static function!`); 
  }
}
const p = new Person('orchid'); 
// 結(jié)果: hello1 orchid, this is an inner function!
p.hello2();   
// 結(jié)果: hello2 orchid, this is a prototype function!
Person.hello3();   
// 結(jié)果: hello3 Person, this is a static function!
對應(yīng)的原型對象實現(xiàn)
function Person(name) {
  this.name = name;
  // 與上面的 hello1 對應(yīng)
  function hello1() {
     console.log(`hello1 ${name}, this is an inner function!`)
  }
  hello1();
}
// 與上面的 hello2 對應(yīng)
Person.prototype.hello2 = function() {
  console.log(`hello2 ${this.name}, this is a prototype function!`);
}
// 與上面的 static 方法 hello3 對應(yīng)
Person.hello3  = function() {
  console.log(`hello3 ${this.name}, this is a static function!`);
}
const p = new Person('orchid');
// 結(jié)果: hello1 orchid, this is an inner function!
p.hello2();    
// 結(jié)果: hello2 orchid, this is a prototype function!
Person.hello3();   
// 結(jié)果: hello3 Person, this is a static function!

相信你通過上面的例子已經(jīng)知道了為什么說class只是一種語法糖了,代碼的確是簡單而且容易閱讀了。
上面就是一個將es6轉(zhuǎn)化為原型對象的代碼實現(xiàn)。es6其實就是將class語法轉(zhuǎn)成了原型對象實現(xiàn),底部還是原型對象的代碼。其實class就是一個函數(shù)而已。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容