我通常看到我们应该在 apply 方法中使用数组,在 call 方法中使用参数数组:
如果我执行以下操作(调用方法将返回未定义):
var namelist = {
f:'first name',
l:'last name'
}
function func(a,b){
console.log(this[a]+' '+this[b])
}
func.call(namelist,['f','l'])
//undefined undefined
func.apply(namelist,['f','l'])
//first name last name
但是,看看这里 call 和 apply 方法都有效:
String.prototype.toUpperCase.call(['a','b','c']) //returns 'A,B,C'
String.prototype.toUpperCase.apply(['a','b','c']) //returns 'A,B,C'
为什么调用方法有效?
如果我这样使用:
String.prototype.toUpperCase.call('a','b','c')
//this would return 'A' only.
最佳答案
call
的第一个参数和apply
是函数的上下文,值为this
.
But, look here both call and apply method works:
String.prototype.toUpperCase.call(['a','b','c']) //returns 'A,B,C' String.prototype.toUpperCase.apply(['a','b','c']) //returns 'A,B,C'
是的,这与您的示例完全不同。您仅将一个参数传递给每个 call
和apply
,所以它们是相同的。你正在传递同样的this
用这两种方法。它们是相同的调用。
String.prototype.toUpperCase.call('a','b','c')
//this would return 'A' only.
是的,因为你只通过了'a'
如this
至toUpperCase
。它会用 apply('a', 'b', 'c')
做同样的事情(如果不是错误的话)再次,因为您只通过了 'a'
如this
至toUpperCase
。不同的是apply
如果您尝试给它提供两个以上的参数,则会引发错误。
原答案:
这不是用 call
传递参数的方式.
使用func.call(namelist, 'f', 'l')
.
apply
接受一个参数数组。 call
只是接受参数。
关于javascript - 传递数组时,调用和 apply 都会为 String.prototype.toUppercase 产生相同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25151862/