js-ES6學習筆記-Class(2)

來源:互聯網
上載者:User

標籤:bind   關鍵字   new   err   定義   提取   模式   erro   類的方法   

1、與函數一樣,類也可以使用運算式的形式定義。

const MyClass = class Me {  getClassName() {    return Me.name;  }};

這個類的名字是MyClass而不是Me,Me只在Class的內部代碼可用,指代當前類。

如果類的內部沒用到的話,可以省略Me,也就是可以寫成下面的形式。

2、採用Class運算式,可以寫出立即執行的Class。

let person = new class {  constructor(name) {    this.name = name;  }  sayName() {    console.log(this.name);  }}(‘張三‘);person.sayName(); // "張三"

3、私人方法是常見需求,但 ES6 不提供,只能通過變通方法類比實現。

一種做法是在命名上加以區別。

class Widget {  // 公有方法  foo (baz) {    this._bar(baz);  }  // 私人方法  _bar(baz) {    return this.snaf = baz;  }  // ...}

這種命名是不保險的,在類的外部,還是可以調用到這個方法。

另一種方法就是索性將私人方法移出模組,因為模組內部的所有方法都是對外可見的。

class Widget {  foo (baz) {    bar.call(this, baz);  }  // ...}function bar(baz) {  return this.snaf = baz;}

上面代碼中,foo是公有方法,內部調用了bar.call(this, baz)。這使得bar實際上成為了當前模組的私人方法。

還有一種方法是利用Symbol值的唯一性,將私人方法的名字命名為一個Symbol值。

const bar = Symbol(‘bar‘);const snaf = Symbol(‘snaf‘);export default class myClass{  // 公有方法  foo(baz) {    this[bar](baz);  }  // 私人方法  [bar](baz) {    return this[snaf] = baz;  }  // ...};

上面代碼中,bar和snaf都是Symbol值,導致第三方無法擷取到它們,因此達到了私人方法和私人屬性的效果。

4、類的方法內部如果含有this,它預設指向類的執行個體。但是,必須非常小心,一旦單獨使用該方法,很可能報錯。

class Logger {  printName(name = ‘there‘) {    this.print(`Hello ${name}`);  }  print(text) {    console.log(text);  }}const logger = new Logger();const { printName } = logger;printName(); // TypeError: Cannot read property ‘print‘ of undefined

如果將這個方法提取出來單獨使用,this會指向該方法運行時所在的環境,因為找不到print方法而導致報錯。

一個比較簡單的解決方案是,在構造方法中綁定this,這樣就不會找不到print方法了。

class Logger {  constructor() {    this.printName = this.printName.bind(this);  }  // ...}

另一種解決方案是使用箭頭函數。

class Logger {  constructor() {    this.printName = (name = ‘there‘) => {      this.print(`Hello ${name}`);    };  }  // ...}

還有一種解決方案是使用Proxy,擷取方法的時候,自動綁定this。

5、類和模組的內部,預設就是strict 模式,所以不需要使用use strict指定運行模式。只要你的代碼寫在類或模組之中,就只有strict 模式可用。

6、name屬性總是返回緊跟在class關鍵字後面的類名。

class Point {}Point.name // "Point"

 

js-ES6學習筆記-Class(2)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.