快速學習this指向

2021-09-22 12:44:36 字數 1688 閱讀 9331

最近接觸react和react native裡面涉及到this指向的問題,如果沒弄清楚,很容易出錯,而之前用vue框架,this指向帶來的問題並不多,所以遺忘不少,現特定整理總結一下,複習和備份一下,同時和大家分享。

普通函式;this指向呼叫函式的最近乙個上下文,通俗點理解就是呼叫函式所在的物件;

//在全域性作用域下

function fn()

fn() //指向呼叫上下文(此處為window) 可以看作 window.fn()

let obj =

}obj.fn() //指向obj,因為其上下文是obj

obj.fn_1 = fn

obj.fn_1() //指向obj

fn_1 = obj.fn

fn_1() //指向window ,其上下文是window

建構函式;正常情況下this指向建立的例項,如例一

//例一:

function f()

let obj = new f();

obj.b = 4

console.log(obj) //

同時,建構函式是可以手動指定乙個返回值,該返回如果是物件則不做任何操作,如果不是乙個物件,則會先試著轉換為乙個物件再返回,此刻例項的物件則為手動設定的返回物件,沒有設定手動設定返回的建構函式可以看作

function f()

箭頭函式;this指向函式宣告時的上下文

let fn_arrow = () => ;     

fn_arrow() // window

let obj =

obj.fn() //還是window,而不是指向呼叫函式的obj

//再看個例子

let obj =

return fn

}, fn_n()

return fn }}

let fn_arrow = obj.fn_a(); // this => obj

let fn_normal = obj.fn_n(); // this => obj

fn_arrow(); // this => obj

fn_normal(); //this => window

思考:let fn = obj.fn_a;

fn()() // 列印出來的是那兩個物件

console.log(this)

this.a = a;

this.b = b

return this.a + this.b + this.c

}let obj =

f.call(obj,2,4) //16

bind

永久的將this繫結到第乙個引數上

function f();

let obj =

let fn = f.bind(obj)

fn() //

在react中如果是元件內自定義函式,需要在建構函式中使用bind繫結this指向元件this

或者在定義時使用箭頭函式,以防止this指向執行上下文造成程式錯誤

this指向的學習

mdn上定義 函式的呼叫方式決定了 this 的值 執行時繫結 this 不能在執行期間被賦值,並且在每次函式被呼叫時 this 的值也可能會不同.個人認為this是要結合上下文的時候判斷他的指向,在全域性執行環境中,this指向的是window.在函式中,this指向看 前面的物件是誰就指向誰 下...

this指向問題(學習筆記)

總的來說 this指的就是呼叫函式的那個物件。1.匿名函式的執行環境具有全域性性,因此其 this 物件通常指向 window。var name the window var obj console.log obj.getname the window2.如果是一般函式,this指向全域性物件win...

JavaScript this指向 學習

函式預編譯過程 this window 全域性作用域裡 this window obj.func func 裡的this指向obj 誰呼叫 this就指向誰 var name 222 var a var fun a.say fun 在全域性執行 沒人呼叫 this指向 window a.say 在a...