打算記流水賬一般細(xì)數(shù)一下 React 中的 this 指向問(wèn)題,具體流程按事件三要素:起因,經(jīng)過(guò),結(jié)果。哈哈哈哈哈!
起因:
眾所周知,React 的設(shè)計(jì)是響應(yīng)式的,使用者無(wú)需操縱 DOM,操縱數(shù)據(jù),頁(yè)面就會(huì)渲染更新。
數(shù)據(jù)一變就更新,是更新所有的 DOM 嗎?當(dāng)然不是,哪些變了就重新渲染哪些。那就要對(duì)數(shù)據(jù)變化前后的 DOM 進(jìn)行比較。直接對(duì)比真實(shí) DOM 嗎?這樣性能會(huì)很低,React 比較的是虛擬 DOM,虛擬 DOM 也是對(duì)象,只不過(guò)相較真實(shí) DOM而言,少了很多屬性,更“輕”。
如何寫(xiě)虛擬 DOM 呢?原生JS我們可以使用 document.createElement() 方法,創(chuàng)建節(jié)點(diǎn)。React 中也可以通過(guò) React.createElement(component, props, children),但是呢這種寫(xiě)法遇見(jiàn)多層嵌套,就能讓人眼花繚亂。于是 JSX “橫空出世”,JSX 其實(shí)就是,React.createElement 的語(yǔ)法糖,但是我們用起來(lái)更加方便,可以直接寫(xiě)成 <p id="test">hello</p> 這種形式。
但是呢問(wèn)題又又來(lái)了!JSX 語(yǔ)法是不被 webpack 識(shí)別的,webpack 默認(rèn)只能處理 .js 后綴名的文件,所以需要借助 Babel 這個(gè) JavaScript 編譯器,而 babel 開(kāi)啟了嚴(yán)格模式 **
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import React, { Component } from 'react' export default class index extends Component { // speak(){ // console.log(this)//輸出undefined // } speak = () => console.log( this ) //輸出該組件 render() { return ( <div> <button onClick={ this .speak}>按鈕</button> </div> ) } } |
this 本質(zhì)上就是指向它的調(diào)用者,this 是在函數(shù)運(yùn)行時(shí)才綁定,JS 里邊普通函數(shù)都是 window 調(diào)用的,所以指向 window,開(kāi)啟了嚴(yán)格模式之后是 undefined。
1
2
3
|
( function (){ console.log( this ) //window })() |
在 JSX 中傳遞的事件不是一個(gè)字符串(在原生 JS 的中監(jiān)聽(tīng)事件,采用的是回調(diào)函數(shù)的形式,在Vue中給監(jiān)聽(tīng)事件傳遞的是字符串變量),而是一個(gè)函數(shù)(如上面的:onClick={this.speak}),此時(shí)onClick即是中間變量,最終是由React調(diào)用該函數(shù),而因?yàn)殚_(kāi)啟了嚴(yán)格模式的緣故,this 是undefined,所以處理函數(shù)中的this指向會(huì)丟失。
經(jīng)過(guò):
事實(shí)上我們需要的是 this 指向當(dāng)前實(shí)例化對(duì)象,無(wú)疑會(huì)使代碼編寫(xiě)方便很多。類(lèi)式組件里邊有兩地方的this恰好指向當(dāng)前實(shí)例化對(duì)象。
1.構(gòu)造函數(shù)
類(lèi)式組件里面的構(gòu)造器里面的this是指向?qū)嵗龑?duì)象的,這是 ES6 類(lèi)的特性,
眾所周知 Javascript 里面是沒(méi)有像 C++,JAVA 里面的的類(lèi)的概念,ES6 類(lèi)的實(shí)現(xiàn)也是基于原型鏈來(lái)實(shí)現(xiàn)的,
在 ES6 以前實(shí)例化一個(gè)對(duì)象應(yīng)該這樣:
1
2
3
4
5
6
7
8
9
|
function Animal(name, age) { this .name = name this .age = age } Animal.prototype.say = function () { console.log( this .name) } const Dog = new Animal( 'dog' , 3) Dog.say() //會(huì)在控制臺(tái)打印出dog |
其中的 new 運(yùn)算符,先產(chǎn)生了一個(gè)空對(duì)象 {},然后生成一個(gè) this 指針,將 this 指針指向這個(gè)空對(duì)象;運(yùn)行構(gòu)造函數(shù)時(shí),就相當(dāng)于{}.name=dog,{}.age=3一樣的為這個(gè)對(duì)象動(dòng)態(tài)添加屬性。最后將這個(gè)生成好的對(duì)象付給 Dog,
當(dāng)我們使用 ES6 的 class 來(lái)聲明上面這個(gè)類(lèi)的話(huà),代碼如下:
1
2
3
4
5
6
7
8
9
10
11
|
class Animal { constructor(name, age) { this .name = name this .age = age } say() { console.log( this .name) } } const Dog = new Animal( 'dog' , 3) Dog.say() //會(huì)在控制臺(tái)打印出dog |
類(lèi)實(shí)現(xiàn)和上面應(yīng)該大差不差,所以this是指向?qū)嵗龑?duì)象的。
2.render 函數(shù)
render 函數(shù)里面的 this,也是指向?qū)嵗摹樯赌兀?/p>
首先 render 方法是在類(lèi)式組件的原型上邊的,React發(fā)現(xiàn)組件是使用類(lèi)定義的時(shí)候,后邊就會(huì) new 出來(lái)該類(lèi)的實(shí)例,注意這個(gè)實(shí)例是 React 幫你 new 出來(lái)的,隨后實(shí)例調(diào)用 render 方法,將虛擬 DOM 轉(zhuǎn)換為真實(shí) DOM,所以 render 中的this 就是指向?qū)嵗吘故撬{(diào)用的嘛!,類(lèi)似的呢,render 是一個(gè)生命周期鉤子,那其他的生命周期鉤子里面的 this也是指向?qū)嵗M件的。
3.bind 和箭頭函數(shù)
解決 this 問(wèn)題呢,要有兩個(gè)知識(shí)儲(chǔ)
(1)bind
call apply bind 都是定義在函數(shù)原型上邊的,用來(lái)改變函數(shù) this 指向,傳入的第一個(gè)參數(shù)是 this,后面的參數(shù)就是fun1的參數(shù)
區(qū)別:
- call 和 bind 傳給調(diào)用的函數(shù)是可以傳多個(gè) apply 則是將參數(shù)放進(jìn)一個(gè)數(shù)組
- call 和 apply 返回立即執(zhí)行函數(shù),bind 返回新的函數(shù),bind()() 也是立即執(zhí)行
- 使用 bind 綁定 this 后,該函數(shù)里面的 this 不能變化了,不論是誰(shuí)調(diào)用
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
let aa = { fun1: function (a,b){ console.log( this ) console.log(a-b); } } let bb = { fun2: function (a,b){ console.log( this ) console.log(a+b); } } aa.fun1.call(bb,11,22); //bb-11 bb.fun2.apply(aa,[11,22]); //aa 33 aa.fun1.bind(bb,11,22)(); //bb -11 |
(2)箭頭函數(shù)
箭頭函數(shù):箭頭函數(shù)并不會(huì)創(chuàng)建自己的執(zhí)行上下文,所以箭頭函數(shù)中的this都是外層的this,會(huì)向外作用域中,一層層查找this,直到有 this 的定義
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
const A = { arrow:() =>{ console.log( this ) //window }, func: function (){ this .arrow() //window console.log( this ) //A setTimeout(() => { console.log( this ) //A }); } } A.arrow() A.func() |
結(jié)果:
解決方法俺會(huì)兩,嘿嘿!
方法一:在構(gòu)造函數(shù)中使用bind
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import React, { Component } from 'react' export default class index extends Component { constructor(){ super () this .speak = this .speak.bind( this ) /*解決類(lèi)中的this問(wèn)題:this.speak = this.speak.bind(this),構(gòu)造器里面的this默認(rèn)指向?qū)嵗龑?duì)象, 實(shí)例對(duì)象通過(guò)原型鏈在類(lèi)的原型上找著fnc函數(shù),通過(guò)bind函數(shù)將其this指向改為實(shí)例對(duì)象,并返回一個(gè)新的函數(shù) 再將這個(gè)新的函數(shù)給實(shí)例,并取名為fnc*/ } speak(){ console.log( this ) //輸出當(dāng)前實(shí)例對(duì)象 } render() { return ( <div> <button onClick={ this .speak}>按鈕</button> </div> ) } } |
方法二:將箭頭函數(shù)賦值給類(lèi)的屬性
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import React, { Component } from 'react' export default class index extends Component { speak = () =>{ console.log( this ) } render() { return ( <div> <button onClick={ this .speak}>按鈕</button> </div> ) } } //需要傳參的話(huà),可以使用函數(shù)柯里化的思想 |
注意:性能存在差異
使用箭頭函數(shù)來(lái)解決性能會(huì)比較低,因?yàn)榧^函數(shù)不是方法,它們是匿名函數(shù)表達(dá)式,所以將它們添加到類(lèi)中的唯一方法是賦值給屬性。前面介紹ES6的類(lèi)的時(shí)候可以看出來(lái),ES 類(lèi)以完全不同的方式處理方法和屬性
方法被添加到類(lèi)的原型中,而不是每個(gè)實(shí)例定義一次。
類(lèi)屬性語(yǔ)法是為相同的屬性分配給每一個(gè)實(shí)例的語(yǔ)法糖,實(shí)際上會(huì)在 constructor里面這樣實(shí)現(xiàn):
1
2
3
4
|
constructor(){ super () this .speak = () => {console.log( this )} } |
這意味著新實(shí)例被創(chuàng)建時(shí),函數(shù)就會(huì)被重新定義,丟失了JS實(shí)例共享原型方法的優(yōu)勢(shì)。而方法一,只是在生成實(shí)例時(shí)多了一步 bind 操作,在效率與內(nèi)存占用上都有極大的優(yōu)勢(shì)
以上就是詳解React中的this指向的詳細(xì)內(nèi)容,更多關(guān)于React中的this指向的資料請(qǐng)關(guān)注服務(wù)器之家其它相關(guān)文章!
原文鏈接:https://juejin.cn/post/6954636599892279304