1. this和method
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