JavaScript 中 fn() 和 fn.call() 的区别
Difference between fn() and fn.call() in JavaScript
var tempFn = function(someText){
console.log(someText);
}
tempFn('siva');
// where I simply call the function with text 'siva'
对比
tempFn.call(this,'siva');
// where I call the function using call method
这些方法有什么区别?
当您使用 call
形式时,您将明确说明将调用该函数的上下文。
当您的函数执行时,上下文将决定 this
的值。
在你的例子中,你传递的是 this
无论如何这将是默认值,所以这是一个空操作。此外,您的 tempFn
函数不会调用 this
关键字,因此如果您传入不同的范围也没关系。
var tempFn = function(someText){
console.log(someText);
}
tempFn('siva');
// where I simply call the function with text 'siva'
对比
tempFn.call(this,'siva');
// where I call the function using call method
这些方法有什么区别?
当您使用 call
形式时,您将明确说明将调用该函数的上下文。
当您的函数执行时,上下文将决定 this
的值。
在你的例子中,你传递的是 this
无论如何这将是默认值,所以这是一个空操作。此外,您的 tempFn
函数不会调用 this
关键字,因此如果您传入不同的范围也没关系。