他山之石,可以攻玉——匿名reference type: this

1. thismethod

let user={
  name: "Jason",
  showName() { alert(this.name); }
}
alert(user.showName()); //Jason

定義在對(duì)象內(nèi)部的function,我們稱(chēng)作method。method往往需要access對(duì)象的其他property,往往是data, 這個(gè)時(shí)候就需要this關(guān)鍵字,在method內(nèi)部通過(guò)this.propertyName來(lái)獲取。

this的其他用法:

this的用法非常廣泛,它完全可以被應(yīng)用在任何函數(shù)的內(nèi)部,不僅僅限于method,在C++或者其他一些語(yǔ)言中,this和對(duì)象是捆綁的(bound),但在JS中不是這樣。this指向的對(duì)象由函數(shù)運(yùn)行環(huán)境(execution context)決定。this的維基介紹

2. 調(diào)用method的方式

有this信息的調(diào)用方式:

user.showName();
user["showName"]();

復(fù)雜的調(diào)用方式很有可能丟失了this信息,比如:

(method=user.showName)();

這是因?yàn)椋篸ot operator .返回的是Reference Type, 里面包含了(base,name, strict)信息
base is the object.
name is the property.
strict is true if use strict is in effect.
當(dāng)我們對(duì)Reference Type進(jìn)一步做其他運(yùn)算,然后再(),Reference Type轉(zhuǎn)換成了function,丟失了base/object信息。

3. return this實(shí)現(xiàn)chained method calls

let obj={
  step: 0,
  up() {
    this.step++;
    return this;
  },
  down() {
    this.step--;
    return this;
  },
  showStep() {
    alert(this.step);
  }
}

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

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

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