- 默認綁定 // 沒人綁定,this => window
- 隱式綁定 // 誰調用this指向誰
- 顯示綁定 // bind call apply
- 構造器調用。(構造器裏的this指向返回的這個對象)這裏可以聯繫new的原理過程
new過程發生的事情
- 創建(或者說構造)一個全新的對象。
- 這個新對象會被執行[[ 原型]] 連接。(proto__: Obj.prototype)
- 這個新對象會綁定到函數調用的this。
- 如果函數沒有返回其他對象,那麼new 表達式中的函數調用會自動返回這個新對象。
用來指定函數內部的this指向,以下是bind的源碼
Function.prototype.bind = function(){
var self = this, // 保存原函數
context = [].shift.call( arguments ), // 需要綁定的this上下文
args = [].slice.call( arguments ); // 剩餘的參數轉成數組
console.log(self)
return function(){ // 返回一個新的函數
return self.apply( context, [].concat.call( args, [].slice.call( arguments ) ) );
// 執行新的函數的時候,會把之前傳入的context當作新函數體內的this
// 並且組合兩次分別傳入的參數,作爲新函數的參數
}
};
var obj = {
name: 'sven'
};
var func = function( a, b, c, d ){
console.log ( this.name ); // 輸出:sven
console.log ( [ a, b, c, d ] ) // 輸出:[ 1, 2, 3, 4 ]
}.bind( obj, 1, 2 );
func( 3, 4 );
對this的應用
var a = 123,
b = 234;
function text() {
var a = 111,
b = 123;
console.log(this.a)
console.log(this.b)
}
var n = new text() // new操作符相當於函數執行,返回一個對象,this綁定在{}上
console.log(n.a)
console.log(n.b)