簡介
基本上骄瓣,ES6 的class可以看作只是一個(gè)語法糖,它的絕大部分功能耍攘,ES5 都可以做到榕栏,新的class寫法只是讓對(duì)象原型的寫法更加清晰畔勤、更像面向?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對(duì)象上面起暮,所以類的新方法可以添加在prototype對(duì)象上面。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命令生成對(duì)象實(shí)例時(shí)五嫂,自動(dòng)調(diào)用該方法颗品。一個(gè)類必須有constructor方法,如果沒有顯式定義沃缘,一個(gè)空的constructor方法會(huì)被默認(rèn)添加躯枢。
constructor方法默認(rèn)返回實(shí)例對(duì)象(即this),完全可以指定返回另外一個(gè)對(duì)象槐臀,這樣new 出來的對(duì)象將不再是該類的實(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對(duì)象上),否則都是定義在原型上(即定義在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è)原型對(duì)象
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)鍵字炼七,對(duì)某個(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 對(duì)象上的
// getOwnPropertyDescriptor 返回某個(gè)對(duì)象屬性某個(gè)屬性的描述對(duì)象
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è)語言升級(jí)到了嚴(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í)所在的對(duì)象待德。
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對(duì)象上調(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è)層級(jí)
// 這時(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í)例對(duì)象(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)部的所有方法都是對(duì)外可見的扳肛。
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á)到了私有方法和私有屬性的效果资铡。但是也不是絕對(duì)不行电禀,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í)例對(duì)象的命令。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í)例化,只能用于繼承谱邪。