React Native填坑之旅--class(番外篇)

無論React還是RN都已經(jīng)邁入了ES6的時(shí)代萝毛,甚至憑借Babel的支持都進(jìn)入了ES7楷力。ES6內(nèi)容很多眉厨,本文主要講解類相關(guān)的內(nèi)容锌奴。

構(gòu)造函數(shù)

定義偵探類作為例子。

ES5的“類”是如何定義的憾股。

function ES5Detective() {
  console.log('##ES5Detective contructor');
}

ES6定義類:

class ES6Detective {
  constructor() {
    console.log('Detective constructor');
  }
}

ES6使用了class關(guān)鍵字鹿蜀,而且有專門的constructor。ES5里的function ES5Detective既是類的定義服球,也是構(gòu)造函數(shù)茴恰。

屬性

看看這個(gè)偵探是從哪本書出來的。

ES5:

ES5Detective.prototype.fromBookName = 'who';

ES6:

class ES6Detective {
  detectiveName: string;
  _bookName: string;

  constructor() {
    console.log('Detective constructor');
    this.detectiveName = 'Detective who'; // 屬性
  }
}

ES6 getter & setter

class ES6Detective {
  detectiveName: string;
  _bookName: string;

  constructor() {
    console.log('Detective constructor');
    this.detectiveName = 'Detective who';
    this._bookName = 'who';
  }

  get fromBookName() {
    return this._bookName;
  }

  set fromBookName(value) {
    this._bookName = value;
  }
}

如果只有g(shù)etter沒有setter而賦值的話就會(huì)出現(xiàn)下面的錯(cuò)誤:

detective.bookAuthor = 'A C';
                     ^

TypeError: Cannot set property bookAuthor of #<ES6Detective> which has only a getter

實(shí)例方法

偵探是如何解決案件的有咨。

ES5:

ES5Detective.prototype.solveCase = function(caseName) {
  var dn = this.dectiveName;
  if(!caseName) {
    console.log('SOLVE CASE: ' + dn + ' no case to solve');
  } else {
    console.log('SOLVE CASE: ' + dn + ' get case ' + caseName + ' is solved');
  }
};

或者:

function ES5Detective() {
  this.dectiveName = 'Detective who';
  console.log('##ES5Detective contructor');
  // 實(shí)例方法
  this.investigate = function(scene) {
    console.log('investigate ' + scene);
  }

  this.assistant = "assistant who";
}

ES6:

class ES6Detective {
  detectiveName: string;
  _bookName: string;

  constructor() {
    console.log('Detective constructor');
    this.detectiveName = 'Detective who';
    this._bookName = 'who';
  }

  solveCase(caseName) {
    if(!caseName) {
      console.log('no case to solve');
    } else {
      console.log('case ' + caseName + ' is solved');
    }
  }
}

ES6添加方法非常簡單直接琐簇。ES5中添加實(shí)例方法有兩種方法,一是在prototype里定義座享,一是在構(gòu)造函數(shù)重定義婉商。在構(gòu)造函數(shù)中定義的實(shí)例方法和屬性在每一個(gè)實(shí)例中都會(huì)保留一份,而在原型中定義的實(shí)例方法和屬性是全部實(shí)例只有一份渣叛。

另外丈秩,在ES5的構(gòu)造函數(shù)重定義的實(shí)例方法可以訪問類的私有變量。比如:

function ES5Detective() {
  console.log('##ES5Detective contructor');

  var available: boolean = true; // private field. default income is ZERO.
  this.investigate = function(scene) {
    if (available) {
      console.log('investigate ' + scene);
    } else {
      console.log(`i'm not available`);
    }
  }
}

在其他的方法訪問的時(shí)候就會(huì)報(bào)錯(cuò)淳衙。

if (!available) {
     ^

靜態(tài)方法

ES5:

ES5Detective.countCases = function(count) {
  if(!count) {
    console.log('no case solved');
  } else {
    console.log(`${count} cases are solved`);
  }
};

類名后直接定義方法蘑秽,這個(gè)方法就是靜態(tài)方法。

ES5Detective.countCases();

ES6:

class ES6Detective {
  static countCases() {
    console.log(`Counting cases...`);
  }
}

// call it
ES6Detective.countCases();

繼承

ES6使用extends關(guān)鍵字實(shí)現(xiàn)繼承箫攀。

ES5:

function ES5Detective() {
  var available: boolean = true; // private field.

  this.dectiveName = 'Detective who';
  console.log('##ES5Detective contructor');

  this.investigate = function(scene) {
    // 略 
  }

  this.assistant = "assistant who";
}

ES5Detective.prototype.solveCase = function(caseName) {
  // 略
}

// inheritance
function ES5DetectiveConan() {
  // first line in constructor method is a must!!!
  ES5Detective.call(this);

  this.dectiveName = 'Conan';
}

// inheritance
ES5DetectiveConan.prototype = Object.create(ES5Detective.prototype);
ES5DetectiveConan.prototype.constructor = ES5DetectiveConan;

ES5繼承的時(shí)候需要注意兩個(gè)地方:

  1. 需要在子類的構(gòu)造函數(shù)里調(diào)用SuperClass.call(this[, arg1, arg2, ...])
  2. 子類的prototype賦值為:SubClass.prototype = Object.create(SuperClass.prototype)肠牲,然后把構(gòu)造函數(shù)重新指向自己的:SubClass.prototpye.constructor = SubClass

ES6:

class ES6Detective {
  constructor() {
    console.log('Detective constructor');
    this.detectiveName = 'Detective who';
    this._bookName = 'who';
  }

  solveCase(caseName) {
    if(!caseName) {
      console.log('no case to solve');
    } else {
      console.log('case ' + caseName + ' is solved');
    }
  }

  get fromBookName() {
    return this._bookName;
  }

  set fromBookName(value) {
    this._bookName = value;
  }

  get bookAuthor() {
    return 'Author Who';
  }

  static countCases() {
    console.log(`Counting cases...`);
  }
}

class ES6DetectiveConan extends ES6Detective {
  constructor() {
    super();
    console.log('ES6DetectiveConan constructor');
  }
}

ES6的新語法更加易懂靴跛。

注意:一定要在子類的構(gòu)造方法里調(diào)用super()方法缀雳。否則報(bào)錯(cuò)。

調(diào)用super類內(nèi)容

class ES6DetectiveConan extends ES6Detective {
  constructor() {
    super();
    console.log('ES6DetectiveConan constructor');
  }

  solveCase(caseName) {
    super.solveCase(caseName);

    if(!caseName) {
      console.log('CONAN no case to solve');
    } else {
      console.log('CONAN case ' + caseName + ' is solved');
    }
  }
}

靜態(tài)方法可以被繼承

ES6的靜態(tài)方法可以被繼承梢睛。ES5的不可以肥印。

class ES6Detective {
  static countCases(place) {
    let p = !place ? '[maybe]' : place;
    console.log(`Counting cases...solve in ${p}`);
  }
}

class ES6DetectiveConan extends ES6Detective {
  constructor() {
    super();
    console.log('ES6DetectiveConan constructor');
  }
}

// static method
ES6Detective.countCases();
ES6DetectiveConan.countCases('Japan');

// result
Counting cases...solve in [maybe]
Counting cases...solve in Japan

在子類ES6DetectiveConan并沒有定義任何方法,包括靜態(tài)方法绝葡。但是深碱,在父類和子類里都可以調(diào)用該方法。

甚至藏畅,可以在子類里調(diào)用父類的靜態(tài)方法:

class ES6DetectiveConan extends ES6Detective {
  static countCases(place) {
    let p = !place ? '[maybe]' : place;
    super.countCases(p);
    console.log(`#Sub class:- Counting cases...solve in ${p}`);
  }
}

// result
Counting cases...solve in [maybe]
Counting cases...solve in Japan
#Sub class:- Counting cases...solve in Japan

代碼

https://github.com/future-challenger/ES-Samples/tree/master/class

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末敷硅,一起剝皮案震驚了整個(gè)濱河市,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌竞膳,老刑警劉巖航瞭,帶你破解...
    沈念sama閱讀 219,039評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件诫硕,死亡現(xiàn)場(chǎng)離奇詭異坦辟,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)章办,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,426評(píng)論 3 395
  • 文/潘曉璐 我一進(jìn)店門锉走,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人藕届,你說我怎么就攤上這事挪蹭。” “怎么了休偶?”我有些...
    開封第一講書人閱讀 165,417評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵梁厉,是天一觀的道長。 經(jīng)常有香客問我踏兜,道長词顾,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,868評(píng)論 1 295
  • 正文 為了忘掉前任碱妆,我火速辦了婚禮肉盹,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘疹尾。我一直安慰自己上忍,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,892評(píng)論 6 392
  • 文/花漫 我一把揭開白布纳本。 她就那樣靜靜地躺著窍蓝,像睡著了一般。 火紅的嫁衣襯著肌膚如雪繁成。 梳的紋絲不亂的頭發(fā)上吓笙,一...
    開封第一講書人閱讀 51,692評(píng)論 1 305
  • 那天,我揣著相機(jī)與錄音朴艰,去河邊找鬼观蓄。 笑死,一個(gè)胖子當(dāng)著我的面吹牛祠墅,可吹牛的內(nèi)容都是我干的侮穿。 我是一名探鬼主播,決...
    沈念sama閱讀 40,416評(píng)論 3 419
  • 文/蒼蘭香墨 我猛地睜開眼毁嗦,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼亲茅!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,326評(píng)論 0 276
  • 序言:老撾萬榮一對(duì)情侶失蹤克锣,失蹤者是張志新(化名)和其女友劉穎茵肃,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體袭祟,經(jīng)...
    沈念sama閱讀 45,782評(píng)論 1 316
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡验残,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,957評(píng)論 3 337
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了巾乳。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片您没。...
    茶點(diǎn)故事閱讀 40,102評(píng)論 1 350
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖胆绊,靈堂內(nèi)的尸體忽然破棺而出氨鹏,到底是詐尸還是另有隱情,我是刑警寧澤压状,帶...
    沈念sama閱讀 35,790評(píng)論 5 346
  • 正文 年R本政府宣布仆抵,位于F島的核電站,受9級(jí)特大地震影響种冬,放射性物質(zhì)發(fā)生泄漏镣丑。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,442評(píng)論 3 331
  • 文/蒙蒙 一碌廓、第九天 我趴在偏房一處隱蔽的房頂上張望传轰。 院中可真熱鬧,春花似錦谷婆、人聲如沸慨蛙。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,996評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽期贫。三九已至,卻和暖如春异袄,著一層夾襖步出監(jiān)牢的瞬間通砍,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,113評(píng)論 1 272
  • 我被黑心中介騙來泰國打工烤蜕, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留封孙,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 48,332評(píng)論 3 373
  • 正文 我出身青樓讽营,卻偏偏與公主長得像虎忌,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子橱鹏,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,044評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容