0x00、從我對(duì)this的感想說(shuō)起
JavaScript中的this機(jī)制是一個(gè)令人非常苦惱的機(jī)制,即使你在寫(xiě)JS代碼中可以去盡量避免它,但是當(dāng)去閱讀一些源代碼或者大牛的代碼時(shí)候你卻依舊繞不開(kāi)它,而且作為一個(gè)很常用機(jī)制之一,this當(dāng)然有他足夠優(yōu)雅的一面,那么何不去發(fā)現(xiàn)它奧秘的一面,并盡量馴服它了
0x01、為什么要運(yùn)用this
先看一個(gè)函數(shù)的傳入?yún)?shù)為一個(gè)對(duì)象的例子
- demo1:
function identify(context){
return context.name.toUpperCase();
}
var edg = {
name:'qi'
}
identify(edg); //QI,其中egd作為對(duì)象作為參數(shù)被傳入函數(shù)中
在這個(gè)例子的基礎(chǔ)上,我們來(lái)增加復(fù)雜點(diǎn)實(shí)現(xiàn)一個(gè)函數(shù)復(fù)合調(diào)用
- demo2:
function identify(context){
return context.name.toUpperCase();
}
function upIde(context){
var a = 'hello' + identify(context);
console.log(a);
return a
}
var edg = {
name:'qi'
}
identify(edg); //QI
upIde(edg); //'helloQI',只有upIde()和identify()的形參需要保持一致性才可以得到了我們想要的結(jié)果
那么使用this可以如何去解決demo2中的效果了
- this-demo:
function identify(){
return this.name.toUpperCase();
}
function upIde(){
var a = 'hello'+identify.call(edg);
console.log(a);
}
var edg = {
name:'qi'
}
identify.call(edg); //QI
upIde.call(edg); //'helloQI'
上面的demo運(yùn)用call()方法,將this指向edg對(duì)象,從而實(shí)現(xiàn)了和demo2中函數(shù)傳對(duì)象作為參數(shù)一樣的效果。
___總結(jié): ___ 通過(guò)對(duì)比我們可以發(fā)現(xiàn)this提供了一種更優(yōu)雅的方式來(lái)隱隱式“ 傳遞”一個(gè)對(duì)象引用,這樣API的設(shè)計(jì)更簡(jiǎn)潔和易于復(fù)用;而且伴隨你使用模式越來(lái)越復(fù)雜, 顯式傳遞上下文對(duì)象(demo2中演示的)會(huì)讓代碼變得越來(lái)越混亂, 使用this則不會(huì)這樣。