另外,可以看看這篇文章:https://www.cnblogs.com/pengshengguang/p/11105323.html
this對象是在運行時基於函數的執行環境綁定的:
-
在全局函數中,this—>window
-
在函數中
1、作爲對象的方法來調用 this—>當前的對象
2、作爲普通的函數調用 this—>window
(1.2可總結爲 看函數名前面是否有“.” ,有的話, “.”前面是誰,this就是誰;沒有的話this就是window )
3、作爲構造函數和new使用 this—>構造函數內部新創建的對象
4、被call或者是apply調用(函數上下文調用) this—>第一個參數
5、立即執行函數中的this永遠都是window
6、箭頭函數不綁定this,會捕獲其所在的上下文的this值,作爲自己的this值。通過 call() 或 apply() 方法調用一個函數時,只傳入了一個參數,對 this 並沒有影響
(function() { return [ (() => this.x).bind({ x: 'inner' })() ]; })() // undefined (function() { return [ (() => this.x).bind({ x: 'inner' })() ]; }).call({ x: 'outer' }); // ['outer']
一道this面試題
var num = 20;
var obj = {
num: 30,
fn: (function(num) {
this.num *= 3;
num += 15;
var num = 45;
return function() {
this.num *= 4;
num += 20;
console.log(num);
}
})(num)
};
var fn = obj.fn;
fn(); // ->65
obj.fn(); // ->85
console.log(window.num, obj.num) // ->240, 120
// 1、fn();
// 因爲立即執行函數中的this永遠是window,所以 this.num = 20*3 = 60, num到上一個作用域找到是45
// 輸出num 45+20=65 window.num = 60*40 = 240 obj.num = 30
// 2、obj.fn();
// this指向obj,所以這裏面 this.num = 30,num = 65
// 輸出num 65+20=85 window.num = 240 obj.num = 30*4 = 120