ES6標(biāo)準(zhǔn)入門 摘要 (Class)

簡介

基本上,ES6 的class可以看作只是一個(gè)語法糖,它的絕大部分功能,ES5 都可以做到,新的class寫法只是讓對象原型的寫法更加清晰、更像面向?qū)ο缶幊痰恼Z法而已。

// es5 定義類
function Point(x, y) {
  this.x = x;
  this.y = y;
}

Point.prototype.toString = function () {
  return '(' + this.x + ', ' + this.y + ')';
};

var p = new Point(1, 2);

// es6 定義類

class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }

  toString() {
    return '(' + this.x + ', ' + this.y + ')';
  }
}

var p = new Point(1, 2);
//  es6 的寫法完全可以看作構(gòu)造函數(shù)的另一種寫法。

// typeof Point // "function"
// Point === Point.prototype.constructor // true

類的數(shù)據(jù)類型就是函數(shù),類本身就指向構(gòu)造函數(shù)。

構(gòu)造函數(shù)的prototype屬性,在 ES6 的“類”上面繼續(xù)存在。事實(shí)上,類的所有方法都定義在類的prototype屬性上面。

class Point {
  constructor() {}

  toString() {}
}

// 等同于下面寫法,定義在prototype上

Point.prototype = {
  constructor() {},
  toString() {},
};

// 在類的實(shí)例上面調(diào)用方法,其實(shí)就是調(diào)用原型上的方法。
let p = new Point();
p.constructor === Point.prototype.constructor // true

由于類的方法都定義在prototype對象上面,所以類的新方法可以添加在prototype對象上面。Object.assign方法可以很方便地一次向類添加多個(gè)方法。

class Point {}
// 向類添加兩個(gè)新方法
Object.assign(Point.prototype, {
  toString(){},
  toValue(){}
});

類的內(nèi)部所有定義的方法,都是不可枚舉的(non-enumerable)

class Point {
  constructor(x, y) {
    // ...
  }

  toString() {
    // ...
  }
}

// 返回自身所有可枚舉的屬性組成的數(shù)組
Object.keys(Point.prototype) 
// []

// 返回自身所有(包括不可枚舉)的屬性組成的數(shù)組
Object.getOwnPropertyNames(Point.prototype)
// ["constructor","toString"]

es5行為與其不一致,定義在Point.prototype的屬性方法是可枚舉的。例如Point.prototype.toString = function () {};中的toString是可枚舉的。

constructor 方法

constructor方法是類的默認(rèn)方法,通過new命令生成對象實(shí)例時(shí),自動(dòng)調(diào)用該方法。一個(gè)類必須有constructor方法,如果沒有顯式定義,一個(gè)空的constructor方法會(huì)被默認(rèn)添加。

constructor方法默認(rèn)返回實(shí)例對象(即this),完全可以指定返回另外一個(gè)對象,這樣new 出來的對象將不再是該類的實(shí)例。

class Foo {
  constructor() {
    return Object.create(null);
  }
}

// constructor方法改變了返回值導(dǎo)致一下表達(dá)式返回false
new Foo() instanceof Foo
// false

類必須使用new調(diào)用,否則會(huì)報(bào)錯(cuò)。這是它跟普通構(gòu)造函數(shù)的一個(gè)主要區(qū)別,后者不用new也可以執(zhí)行。

類的實(shí)例

與 ES5 一樣,實(shí)例的屬性除非顯式定義在其本身(即定義在this對象上),否則都是定義在原型上(即定義在class上)。

class Point {
  constructor(x) {
    this.x = x;
  }

  toString() {
    console.logz('a');
  }
}
var point = new Point(1);
var point2 = new Ponint(2);

// 只有x是定義在this上的,toString是定義在原型上的
point.hasOwnProperty('x') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true

// 類的所有實(shí)例共享一個(gè)原型對象
point.__proto__ === point2.__proto__;

// 這也意味著,可以通過實(shí)例的__proto__屬性為“類”添加方法。
point.__proto__.say = function () { return 'hello' };

point.say() // 'hello'
point2.say() // 'hello'

取值函數(shù)(getter)和存值函數(shù)(setter)

與 ES5 一樣,在“類”的內(nèi)部可以使用get和set關(guān)鍵字,對某個(gè)屬性設(shè)置存值函數(shù)和取值函數(shù),攔截該屬性的存取行為。

class MyClass {
  constructor() {
    // ...
  }
  get prop() {
    return 'getter';
  }
  set prop(value) {
    console.log('setter: '+value);
  }
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// 'getter'

// 存值函數(shù)和取值函數(shù)是設(shè)置在屬性的 Descriptor 對象上的
// getOwnPropertyDescriptor 返回某個(gè)對象屬性某個(gè)屬性的描述對象

var descriptor = Object.getOwnPropertyDescriptor( MyClass.prototype, "prop");

"get" in descriptor  // true
"set" in descriptor  // true

Class 表達(dá)式

與函數(shù)一樣,類也可以使用表達(dá)式的形式定義。類的屬性名,也可以采用表達(dá)式。

let fName = 'say';
const MyClass = class Me {
  getClassName() {
    // 在函數(shù)內(nèi)部可以使用Me,但是在函數(shù)外部就必須使用MyClass引用
    return Me.name;
  }

  [fName]() {
    return 'hello'
  }
};

// 在使用的表達(dá)式的時(shí)候,在內(nèi)部沒用到時(shí),可省略類名。
const MyClass = class {}

// 也可以寫出立即執(zhí)行的 Class
let person = new class {
  constructor(name) {
    this.name = name;
  }

  sayName() {
    console.log(this.name);
  }
}('張三');

person.sayName(); // "張三

注意點(diǎn)

  • 嚴(yán)格模式:類和模塊的內(nèi)部,默認(rèn)就是嚴(yán)格模式,考慮到未來所有的代碼,其實(shí)都是運(yùn)行在模塊之中,所以 ES6 實(shí)際上把整個(gè)語言升級到了嚴(yán)格模式。
  • 類不存在變量提升:因?yàn)?ES6 不會(huì)把類的聲明提升到代碼頭部。這種規(guī)定的原因與繼承有關(guān),必須保證子類在父類之后定義。
  • name屬性:由于本質(zhì)上,ES6 的類只是 ES5 的構(gòu)造函數(shù)的一層包裝,所以函數(shù)的許多特性都被Class繼承,包括name屬性。
  • Generator 方法:如果某個(gè)方法之前加上星號(hào)(*),就表示該方法是一個(gè) Generator 函數(shù)。
  • this 的指向:類的方法內(nèi)部如果含有this,它默認(rèn)指向類的實(shí)例,但是如果暴露方法到外部的時(shí)候,this會(huì)指向該方法運(yùn)行時(shí)所在的環(huán)境(由于class內(nèi)部是嚴(yán)格模式,所以this執(zhí)行undefined)
// 有3種方法解決當(dāng)暴露方法給外部時(shí),this指向的問題

// 1、在構(gòu)造函數(shù)中綁定this
class Logger {
  constructor() {
    this.printName = this.printName.bind(this);
  }
}

// 2、使用箭頭函數(shù),箭頭函數(shù)內(nèi)部的this總是指向定義時(shí)所在的對象。
class Obj {
  constructor() {
    this.getThis = () => this;
  }
}

// 3、使用proxy,獲取方法的時(shí)候,自動(dòng)綁定this
function selfish (target) {
  // 用來存儲(chǔ)已綁定過的方法
  const cache = new WeakMap();
  const handler = {
    get (target, key) {
      const value = Reflect.get(target, key);
      // 如果訪問的不是方法,則直接放回值
      if (typeof value !== 'function') {
        return value;
      }
      // 如果是,將綁定完的函數(shù)緩存在cache中
      // 使用原函數(shù)作為key 將綁定好的函數(shù)作為value
      if (!cache.has(value)) {
        cache.set(value, value.bind(target));
      }
      return cache.get(value);
    }
  };
  const proxy = new Proxy(target, handler);
  return proxy;
}

const logger = selfish(new Logger());
// 此時(shí)訪問logger的方法,就是訪問經(jīng)過logger的新實(shí)例調(diào)用bind后得到的方法

靜態(tài)方法

加上static關(guān)鍵字,就表示該方法不會(huì)被實(shí)例繼承,而是直接通過類來調(diào)用,這就稱為“靜態(tài)方法”。

class Foo {
  static say() {
    return 'hello';
  }
  static bar() {
    return this.say();
  }
}

Foo.say() // 'hello'
new Foo().say() // TypeError

// 如果靜態(tài)方法包含this關(guān)鍵字,這個(gè)this指的是類,而不是實(shí)例。
Foo.bar() // 'hello'

// 父類的靜態(tài)方法,可以被子類繼承。
class Bar extends Foo {
}
Bar.say() // 'hello'

// 靜態(tài)方法也是可以從super對象上調(diào)用的

class Baz extends Foo {
  static say() {
    return super.say() + ' Baz'
  }
}
Baz.say() // 'hello Baz'

實(shí)例屬性的新寫法

實(shí)例屬性除了定義在constructor()方法里面的this上面,也可以定義在類的最頂層。

class IncreasingCounter {
  // 實(shí)例屬性_count與取值函數(shù)value()和increment()方法,處于同一個(gè)層級
  // 這時(shí),不需要在實(shí)例屬性前面加上this。
  _count = 0;

  constructor(x) {
    this.x = x; // 定義在this上
  }
  get value() {
    console.log('Getting the current value!');
    return this._count;
  }
  increment() {
    this._count++;
  }
}

靜態(tài)屬性

靜態(tài)屬性指的是 Class 本身的屬性,即Class.propName,而不是定義在實(shí)例對象(this)上的屬性。

現(xiàn)在有一個(gè)提案提供了類的靜態(tài)屬性,寫法是在實(shí)例屬性的前面,加上static關(guān)鍵字。這個(gè)新寫法大大方便了靜態(tài)屬性的表達(dá)。

// 老寫法:ES6 明確規(guī)定,Class 內(nèi)部只有靜態(tài)方法,沒有靜態(tài)屬性
class Foo {
  // ...
}
// 所以只能使用這種方法來添加靜態(tài)屬性
Foo.prop = 1;

// 新寫法:提案
class Foo {
  static prop = 1;
}

私有方法和私有屬性

私有方法和私有屬性,是只能在類的內(nèi)部訪問的方法和屬性,外部不能訪問。這是常見需求,有利于代碼的封裝,但 ES6 不提供,只能通過變通方法模擬實(shí)現(xiàn)。

一種做法是在命名上加以區(qū)別。在名字前加下劃線,表示這是一個(gè)只限于內(nèi)部使用的私有方法。但是,這種命名是不保險(xiǎn)的,在類的外部,還是可以調(diào)用到這個(gè)方法。

class Widget {

  // 公有方法
  foo (baz) {
    this._bar(baz);
  }

  // 私有方法
  _bar(baz) {
    return this.snaf = baz;
  }
}
// 希望外部只訪問foo ,但實(shí)際外部還是能訪問到_bar

另一種方法就是索性將私有方法移出模塊,因?yàn)槟K內(nèi)部的所有方法都是對外可見的。

class Widget {
  foo (baz) {
    bar.call(this, baz);
  }
}

function bar(baz) {
  return this.snaf = baz;
}

foo是公開方法,內(nèi)部調(diào)用了bar.call(this, baz)。這使得bar實(shí)際上成為了當(dāng)前模塊的私有方法。

還有一種方法是利用Symbol值的唯一性,將私有方法的名字命名為一個(gè)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值,一般情況下無法獲取到它們,因此達(dá)到了私有方法和私有屬性的效果。但是也不是絕對不行,Reflect.ownKeys()依然可以拿到它們。

私有屬性的提案

目前,有一個(gè)提案,為class加了私有屬性。方法是在屬性名之前,使用#表示。

class IncreasingCounter {
  #count = 0;
  get value() {
    console.log('Getting the current value!');
    return this.#count;
  }
  increment() {
    this.#count++;
  }
}

// 只能在類的內(nèi)部使用this.#count
const counter = new IncreasingCounter();
counter.#count // 報(bào)錯(cuò)
counter.#count = 42 // 報(bào)錯(cuò)
class Point {
  #x;
  #a;
  #b;
  #xValue = 0;
  constructor(x = 0) {
    this.#x = +x;
  }
  // 通過x 來映射 #x
  // 由于井號(hào)#是屬性名的一部分,使用時(shí)必須帶有#一起使用
  // 所以#x和x是兩個(gè)不同的屬性。
  get x() {
    return this.#x;
  }

  set x(value) {
    this.#x = +value;
  }

  // 私有方法
  #sum() {
    return #a + #b;
  }

  // 私有屬性也可以設(shè)置 getter 和 setter 方法。
  get #x() { return #xValue; }
  set #x(value) {
    this.#xValue = value;
  }
}

私有屬性不限于從this引用,只要是在類的內(nèi)部,實(shí)例也可以引用私有屬性。

class Foo {
  #privateValue = 42;
  static getPrivateValue(foo) {
    return foo.#privateValue;
  }
}

Foo.getPrivateValue(new Foo()); // 42

私有屬性和私有方法前面,也可以加上static關(guān)鍵字,表示這是一個(gè)靜態(tài)的私有屬性或私有方法。

new.target 屬性

new是從構(gòu)造函數(shù)生成實(shí)例對象的命令。ES6 為new命令引入了一個(gè)new.target屬性,該屬性一般用在構(gòu)造函數(shù)之中,返回new命令作用于的那個(gè)構(gòu)造函數(shù)。

如果構(gòu)造函數(shù)不是通過new命令或Reflect.construct()調(diào)用的,new.target會(huì)返回undefined,因此這個(gè)屬性可以用來確定構(gòu)造函數(shù)是怎么調(diào)用的。

在函數(shù)外部,使用new.target會(huì)報(bào)錯(cuò)。

function Person(name) {
  if (new.target !== undefined) {
    this.name = name;
  } else {
    throw new Error('必須使用 new 命令生成實(shí)例');
  }
  // 正常使用new 使用調(diào)用時(shí),new.target === Person
}

Class 內(nèi)部調(diào)用new.target,返回當(dāng)前 Class。

class Rectangle {
  constructor(length, width) {
    console.log(new.target === Rectangle); // true
    this.length = length;
    this.width = width;
  }
}

// 需要注意的是,子類繼承父類時(shí),new.target會(huì)返回子類。

class Square extends Rectangle {
  constructor(length) {
    // 從父類繼承l(wèi)ength、width屬性
    super(length, width);
  }
}

var obj = new Square(3);
// 這里new Square 上面的console輸出 false

利用這個(gè)特點(diǎn),可以寫出不能獨(dú)立使用、必須繼承后才能使用的類。

class Shape {
  constructor() {
    if (new.target === Shape) {
      // 不能直接使用new 調(diào)用,會(huì)報(bào)錯(cuò),除非是子類繼承后使用
      throw new Error('本類不能實(shí)例化');
    }
  }
}

class Rectangle extends Shape {
  constructor(length, width) {
    // 繼承
    super();
    // ...
  }
}

var x = new Shape();  // 報(bào)錯(cuò)
var y = new Rectangle(3, 4);  // 正確,new.target === Rectangle

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

相關(guān)閱讀更多精彩內(nèi)容

  • 簡介 Class 可以通過extends關(guān)鍵字實(shí)現(xiàn)繼承。 子類必須在constructor方法中調(diào)用super方法...
    Upcccz閱讀 192評論 0 0
  • class的基本用法 概述 JavaScript語言的傳統(tǒng)方法是通過構(gòu)造函數(shù),定義并生成新對象。下面是一個(gè)例子: ...
    呼呼哥閱讀 4,203評論 3 11
  • 簡介 類的由來 JavaScript 語言中,生成實(shí)例對象的傳統(tǒng)方法是通過構(gòu)造函數(shù)。下面是一個(gè)例子。 上面這種寫法...
    IT楊閱讀 890評論 0 2
  • ES5關(guān)于類 JavaScript 語言中,生成實(shí)例對象的傳統(tǒng)方法是通過構(gòu)造函數(shù)。 ES6關(guān)于類 ES6 提供了更...
    _羊羽_閱讀 442評論 0 0
  • 簡介 JavaScript語言中,生成實(shí)例對象的傳統(tǒng)方法是通過構(gòu)造函數(shù)。 ES6引入了Class(類)這個(gè)概念,作...
    oWSQo閱讀 445評論 0 0

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