【问题标题】:Both call and apply produce the same result for String.prototype.toUppercase when passing an array [duplicate]传递数组时,调用和应用都会为 String.prototype.toUppercase 产生相同的结果[重复]
【发布时间】: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


【解决方案1】:

callapply 的第一个参数是函数的上下文,即this 的值。

但是,在这里调用和应用方法都有效:

String.prototype.toUpperCase.call(['a','b','c']) //returns 'A,B,C'
String.prototype.toUpperCase.apply(['a','b','c']) //returns 'A,B,C'

是的,这与您的示例完全不同。您只将一个参数传递给callapply,因此它们是相同的。您使用这两种方法传递了相同的this。它们是相同的调用。

String.prototype.toUpperCase.call('a','b','c')

//这将只返回“A”。

是的,因为您只将'a' 作为this 传递给toUpperCase。它会再次使用apply('a', 'b', 'c') 做同样的事情(如果它不是错误的话),因为你只将'a' 作为this 传递给toUpperCase。不同之处在于 apply 如果您尝试为其提供两个以上的参数,则会引发错误。


原答案:

这不是您使用call 传递参数的方式。

使用func.call(namelist, 'f', 'l')

apply 接受一个参数数组。 call 只接受参数。

【讨论】:

  • 我认为 OP 的实际问题是为什么 callapplyString.prototype.toUpperCase 中产生相同的结果
  • 是的,这就是 call 方法应该是如何工作的,但我给出了 String.prototype.toUpperCase.call(['a','b','c']) 的例子以及为什么这样正在工作...
  • 他们做同样的事情是因为同样的事情。它们是相同的调用。您将数组作为this 传递给这两种方法。 apply(x)call(x) 之间没有区别,它们是相同的。不同之处仅在于他们如何接受论点。 apply(x, [y])call(x, y) 是相同的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
  • 1970-01-01
  • 2013-02-19
  • 1970-01-01
相关资源
最近更新 更多