js中this問題

  1. 默認綁定 // 沒人綁定,this => window
  2. 隱式綁定 // 誰調用this指向誰
  3. 顯示綁定 // bind call apply
  4. 構造器調用。(構造器裏的this指向返回的這個對象)這裏可以聯繫new的原理過程

new過程發生的事情

  1. 創建(或者說構造)一個全新的對象。
  2. 這個新對象會被執行[[ 原型]] 連接。(proto__: Obj.prototype)
  3. 這個新對象會綁定到函數調用的this。
  4. 如果函數沒有返回其他對象,那麼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)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章