this指向及箭頭函式

2021-10-05 14:47:23 字數 2288 閱讀 3875

this 指向問題:一般情況下this的最終指向的是那個呼叫它的物件。

1、全域性作用域或者普通函式中this指向全域性物件window( 注意定時器裡面的this指向window)

// 全域性作用域或者普通函式中this指向全域性物件window( 注意定時器裡面的this指向window)

console.

log(

this);

//window

functionfn(

)window.fn(

);window.

settimeout

(function()

,1000

);

2、方法呼叫中誰呼叫,則this指向誰

// 方法呼叫中誰呼叫this指向誰

var o =}o.

sayhi()

;var btn = document.

queryselector

('button');

btn.

onclick

=function()

btn.

addeventlistener

('click'

,function()

)

3、建構函式中this指向建構函式的例項

// 建構函式中this指向建構函式的例項

function

fun(

)var fun =

newfun()

;

es6中的箭頭函式:

const ccc = (引數列表) =>

const ccc = () =>

1.引數問題:

// 1.1.放入兩個及以上引數

const

sum=

(num1, num2)

=>

// 1.2.放入乙個引數,可以省略括號

// const power = (num) =>

const

power

= num =>

// 1.3.沒有引數,括號不能省略

const

show=(

)=>

2.函式內**量問題:

函式**塊中有多行**時

const

test=(

)=>

// 2.2.函式**塊中只有一行**

// const mul = (num1, num2) =>

const

mul=

(num1, num2)

=> num1 * num2 // 這種寫法,不用寫return,因為它有返回值返回

// 因此引申出另一種情況:原**中沒有return的情況

// const demo = () =>

const

demo=(

)=> console.

log(

'hello demo'

)console.

log(

demo()

);// hello demo undefined

// 呼叫demo()時,會列印 hello demo

// 箭頭函式這種寫法會有返回值,但是log是沒有返回值的,所以返回給demo()函式的是undefined

// 最終列印demo()時會列印出 hello demo undefined

3.箭頭函式的this指向問題:

問題:箭頭函式中的this是如何查詢的了?

答案:向外層作用域一層層地查詢this,直到有this的定義。

settimeout

(function()

,1000

)settimeout((

)=>

,1000

)

const obj =

)settimeout((

)=>

) console.

log(

this);

// obj

}}

測試:

const obj =

)settimeout((

)=>)}

)settimeout((

)=>

)settimeout((

)=>)}

)}}

this指向箭頭函式詳解

本文參考 this 指的是你的函式執行時所在的環境 作用域 全域性環境下 console.log this.document document true 在全域性環境下this始終指向全域性物件,無論是否嚴格模式 在瀏覽器中,this指向window物件 console.log this windo...

箭頭函式this指向問題

前言 線下筆試碰到的題目,發現學習掌握的不透徹,所以回來填坑 const obj1 const obj2 console.log obj1.func.bind obj2 輸出結果為 剛開始很疑惑結果,於是做了個對比 const obj1 const obj2 console.log obj1.fun...

箭頭函式this的指向

什麼是箭頭函式,箭頭函式是es6的新特性,其出現就是為了更好的表示 代替 函式 箭頭函式 arg1,arg2 當箭頭函式只有乙個引數 arg1 console.log arg1 箭頭函式隱式return arg1 arg1 等價於 arg1 return arg1箭頭函式的this不同於以上所有情況...