AdSense

網頁

2017/10/30

JavaScript 函式 Function的call()

JavaScript function的call()方法可用來呼叫函式並傳入給定的this值及其他參數。

語法如下

function.call(thisArg, arg1, arg2, ...)

thisArg為傳入函式的thisarg1, arg2, ...等為傳入函式的參數。


下面範例使用JavaScript的嚴格模式(strict mode),觀察執行結果的差異。

"use strict"; // 嚴格模式

function func(param1, param2){
  console.log(this);
  console.log(param1);
  console.log(param2);
}

console.log('===== func() =====');
func('foo','bar');

console.log('=== func.call() ==');
func.call( {a:1}, 'foo', 'bar' );

執行結果如下

===== func() =====
undefined
foo
bar
=== func.call() ==
{ a: 1 }
foo
bar

函式func()被呼叫了兩次。第一次用func()直接呼叫,第二次用func.call()呼叫,傳入call()的第一個參數{ a: 1 }為給定的this

在嚴格模式下直接呼叫函式時,函式中的thisundefined,如果不是嚴格模式則this指向global物件,在瀏覽器中為window物件,在node.js中為node.js的global scope object

不過在使用call()來呼叫func()函式時,因為第一個參數會作為函式中的this,所以印出{ a: 1 }


參考:

沒有留言:

AdSense