es6箭頭函式this問題

2022-05-06 04:45:11 字數 1352 閱讀 5220

最近做vue的專案,發現中用了很多es6中的新特性,隨後開始惡補es6,發現箭頭函式這一簡潔的函式寫法,不過還是感覺不習慣,箭頭函式的格式;

//有引數

var foo = n => console.log(n);

var foo = function (n)

// 沒有引數

var foo = () => 1;

var foo = function ()

// 多個引數

var foo = (n1,n2) => n1+n2;

var foo = function (n1,n2)

//返回值多行要用 {}

var foo = (n) =>

}var foo = function (n)

}//總結:返回值為單行的時候,可以省去return;

箭頭函式中this是乙個空物件,在node.js中測試可發現:

let foo = ()=> 

}

箭頭函式上層還是箭頭函式,那麼就仍然沒有找到,最終都沒有找到的話,那就是window物件了。

var number = 100,

log = console.log.bind("console");

var obj =

}

};obj.print()();

如果上層是function格式的函式,那麼就會繫結到箭頭函式的this

var number = 100,

log = console.log.bind("console");

var obj =

} }obj.print()();

並不是因為箭頭函式內部有繫結this的機制,實際原因是箭頭函式根本沒有自己的this,它的this是繼承外面的,因此內部的this就是外層**塊的this。

產生箭頭函式的繫結,箭頭函式的this不再多變,(根據宣告時,所繫結的執行,而不是執行時的物件) 

function函式this執行時繫結的理解:

//**段1

var number = 10;

function foo () ;

var obj = ;

obj.foo(); //100

//**段2

var number = 10;

var obj =

}obj.foo() //100

function函式this是再**執行時期繫結而不是在宣告時期繫結的,而箭頭函式是根據宣告時繫結執行的,箭頭函式的this不再多變

es6箭頭函式

本例是在了解es6知識後在原來定義函式的基礎上進行理解var searchvalue 查詢匹配物件 var button var input var select button if searchvalue.input undefined button.click else 重新整理 tableli...

es6 箭頭函式

1.單引數 function cheng a 3 let cheng a 3 a a console.log cheng 9 2.多引數 function add a,b let add a,b a b 預設返回值 console.log add 3,9 3.無返回值 function add a,...

ES6 箭頭函式

es6 中,箭頭函式就是函式的一種簡寫形式,使用括號包裹數,跟隨乙個 緊接著是函式體 var getprice function 箭頭函式 var getprice 9.15 箭頭函式不僅僅是讓 變得簡潔,函式中 this 總是繫結總shi 指向物件自身 function person 1000 使...