【发布时间】:2014-09-28 21:15:04
【问题描述】:
我通常看到我们应该在 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.
【问题讨论】:
-
现在无法回答,因为问题已关闭,但我想说您的数组在两种情况下都被转换为字符串,用作
this参数和['a','b','c'].toString() === 'a,b,c'跨度>
标签: javascript