1.this(執行上下文)指向
(1)普通函數中的this:
- 在簡單調用中,非嚴格模式下,指向
window
。嚴格模式下,爲undefined
。
function parent() {
console.log(this);
}
parent();// window
'use strict';
function parent() {
console.log(this);
}
parent(1,2); // undefined
- 作爲某個對象方法調用時,this指向該對象。
- 當該普通函數被間接調用時,即:使用
call()
和apply()
方法調用時,this指向call()和apply()第一個參數。注意:當第一個參數爲null
或者undefined
時,調用函數中的this指向window
哦~~~
function parent() {
console.log(this);
}
const obj = {
name: 'ha'
}
parent.call(obj); // this指向obj對象
- 該普通函數被用作構造函數用new關鍵字構造對象實例時,this指向新建的實例。
(2)箭頭函數中的this:
- 沒有自己的this,內部this的值,依賴於外部非箭頭函數的this。
function regular() {
console.log(this);
const arrowFun = () =>{
console.log(this); // obj
}
arrowFun();
}
const obj = {
name: 'ha'
}
regular.call(obj );
2.構造函數
(1)普通函數
- 普通函數可以作爲構造函數來用,用new去新建對象實例。
(2)箭頭函數
- 不能當做構造函數去用,並且,會報錯。
3.arguments對象
(1)普通函數
- 普通函數內部,arguments爲特殊的類數組對象。包含了函數被調用時的參數列表。
(2)箭頭函數
- 內部是沒有arguments對象,同this一樣,依賴於外部非箭頭函數。
function regular() {
const arrow = () => {
console.log(arguments);
}
arrow();
}
regular(1,2,3);
- 如果你期待從箭頭函數中,獲取其全部的參數,可以用
剩餘參數功能
(the rest parameters feature):
function regular() {
const arrow = (...arg) => {
console.log(arg); // [[1,2,3], 232]
}
arrow([1,2,3], 232);
}
regular(1,2,3);
4.隱式return
(1)普通函數
- 用return去返回一個函數的結果。無return語句,或者return後面無表達式,則返回undefined。
(2)箭頭函數
- 如果函數僅有一個表達式,那麼該表達式的結果會被隱式返回。
const increment = (num) => num + 1;
increment(41); // => 42
5.當作爲回調方法去使用時
(1)普通函數
- 由於普通函數的this,由執行時候確定。那麼當做爲定時器函數或者事件監聽器的回調去執行時,就有this指向的問題了。這時候,你或許需要用
bind()
方法去綁定this值。
(2)箭頭函數
- 箭頭函數的this,由定義它的時候,外部非箭頭函數中this所決定。因此,如果需要將一個函數作爲回調函數去執行,並且,不希望函數中的this發生改變時。那麼,非箭頭函數就是把利器了。
class Hero {
constructor(heroName) {
this.heroName = heroName;
}
logName = () => {
console.log(this.heroName);
}
}
const batman = new Hero('Batman');
setTimeout(batman.logName, 1000); // after 1 second logs "Batman"