我不明白JavaScript中call()方法的意义 [英] I don't understand the point of the call() method in JavaScript
问题描述
请看下面的代码并解释:我做错了什么?
Please look at the code below and explain: what am I doing wrong?
function doStuff(a, b){
return a + b + 1 ;
}
var myContext = {
c: 1,
d: 3
};
// myContext = this (result => 5)
doStuff.call(myContext,myContext.c,myContext.d)
// ... so why doesn't the below work? (result => NaN)
doStuff.call(myContext,this.c,this.d)
// To make the above work, i must replace "this" with "myContext" (result => 5)...
doStuff.call(myContext,myContext.c,myContext.d)
// ...which is no different to...
doStuff(myContext.c,myContext.d)
// ...so what was the point of call() method?
我厚吗?
推荐答案
调用
的要点是设置这个
的值强>功能。由于您的 doStuff
未在函数中使用此
,使用打电话
,这是毫无意义的。
The main point of call
is to set the value of this
within the function. Since your doStuff
doesn't use this
within the function, using call
with it is pointless.
以下是一个重要的例子:
Here's an example where it matters:
function doStuff(a, b) {
return this.sum(a, b);
}
var obj = {
sum: function(a, b) {
return a + b;
}
};
console.log(doStuff.call(obj, 3, 4)); // 7, because `obj` has a `sum` property
console.log(doStuff(3, 4)); // Fails with an error that `this.sum` is not a function
所以为什么以下不起作用? (result => NaN)
so why doesn't the below work? (result => NaN)
doStuff.call(myContext,this.c,this.d)
因为 this.c
在电话之前评估到 doStuff
,使用当前这个
值。如何调用该代码,这个
是(在松散模式下)全局对象(浏览器上的窗口对象),它可能没有 c
或 d
属性。 (在严格模式下,再次假设你如何调用它,你会得到一个例外,因为这个
是 undefined
并且您无法从 undefined
中检索属性。)
Because this.c
is evaluated before the call to doStuff
, using whatever the current this
value is. How you're probably calling that code, this
is (in loose mode) the global object (the window object, on browsers), which probably doesn't have a c
or d
property. (In strict mode, again making assumptions about how you're calling that, you'd get an exception, because this
is undefined
and you can't retrieve properties from undefined
.)
这篇关于我不明白JavaScript中call()方法的意义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!