調用function時,常會在function內的一堆動作中看到this關鍵字,而this就是記錄呼叫function的object。
昨天小複習:預設繫結,this預設的是window;隱含繫結,this綁定的是將function設定為method並呼叫他的object。
基本上call和apply一樣,差在apply參數要放在偽數組裡,call直接用逗號隔開
bind就差很多,bind回傳一個function,而且他強制綁定一個物件,之後再變也沒用
var str = 'Here is
 Global',
		obj1={str:'Here is Obj1', log:logStr},
		obj2={str:'Here is Obj2'};
function logStr(){
	var str = 'Here is Local';
	console.log(this.str)
}
logStr.call(obj1);
logStr.call(obj2);
logStr.call(null);
logStr.call();
logStr.apply(obj1);
logStr.apply(obj2);
logStr.apply(null);
logStr.apply();
logStr();                         
var print = obj1.log;
print();
print.call(obj2);
var afterRunLog = obj1.log();
afterRunLog;
解析:
倒數第二段
obj1的log屬性的logStr function地址另給變數print,執行print。print()等價於logStr()
最後一段
最後一段只是為了比較var print = obj1.log 和var afterRunLog = obj1.log()
logStr function地址另給變數print
logStr function執行完後的結果,另給變數afterRunLog
apply通常用在參數不固定數量時
//要寫一個不固定參數的add
function add(...x){
	var total =0;
	for(let i=0;i<x.length;i++){
		total = total + x[i]
	}
	return total
}
add.apply(null,[1,2,3,4,5]);
var str = 'Here is Global',
		obj1={str:'Here is Obj1', log:logStr},
		obj2={str:'Here is Obj2'};
function logStr(){
	var str = 'Here is Local';
	console.log(this.str)
}
var logObj1 = logStr.bind(obj1);
logObj1();
logObj1.call(obj1);
logObj1.apply(obj2);
logObj1.call();
var dobBindObj2 = logObj1.bind(obj2);
dobBindObj2();
dobBindObj2.call(obj1);
dobBindObj2.apply(obj2);
dobBindObj2.call();
解析:
var str = 'Here is Global';
function logStr(){
	var str = 'Here is Local';
	//小心要切換成"" 因為I'm
	//會報錯Uncaught SyntaxError: Unexpected identifier
	this.str="Hi I'm New";
};
var objNew = new logStr();
console.log(objNew.str);
JavaScript - This (1) - iT 邦幫忙::一起幫忙解決難題,拯救 IT 人的一天
JS中this关键字详解