.apply(Math, arrayName) 如何工作?(javascript) [英] How does .apply(Math, arrayName) work? (javascript)

查看:25
本文介绍了.apply(Math, arrayName) 如何工作?(javascript)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

还有更多 one stackoverflow 问题,关于如何在 javascript 中找到一组值的最小值或最大值.这不是那个问题.

There is more than one stackoverflow question about how to find the min or max of an array of values in javascript. This is not that question.

我想知道为什么传递 .apply() 奇怪的东西作为 this 参数仍然有效.尽管 一篇很好的博文来自 Aaron Crane,关于 Math 对象的 API 如何成为它的样子是的,还有一些事情没有得到解答.

I want to know why passing .apply() strange things as the this argument still works. Despite a good blog post from Aaron Crane on how the Math object's API became what it is, there's still something left unanswered.

以下每个代码片段都有效.我的问题是,如何?对 this 的赋值到底发生了什么,使每一个都可以工作?

Each of the following code snippets work. My question is, how? What exactly is happening with the assignment to this that makes each of these work?

标准结构

var values = [45, 46, 47]
var min = Math.min.apply(Math, values);
alert(min); //45

更奇怪的结构,但范围可能很棘手...

A Weirder Construction, But Scope can be Tricky...

var values = [45, 46, 47]
var min = Math.min.apply(this, values);
alert(min); //45

有点奇怪

var values = [45, 46, 47]
var min = Math.min.apply(global, values);
alert(min); //45

仍然更奇怪,但也许可以使用 b/c 浏览器

Weirder Still, But Maybe Okay b/c Browsers

var values = [45, 46, 47]
var min = Math.min.apply(window, values);
alert(min); //45

很奇怪

var values = [45, 46, 47]
var min = Math.min.apply(null, values);
alert(min); //45

真的很奇怪

var values = [45, 46, 47]
var min = Math.min.apply(undefined, values);
alert(min); //45

推荐答案

TL;DR - Math.min()Math.max() 实际上并没有使用传递给它们的 this 参数,这只是让它们接受参数数组的一种技巧,因为本机 API 仅指定了一个变量列表..apply() 可以接受参数数组,这就是使用它的原因.

TL;DR - Math.min() and Math.max() don't actually use the this argument passed to them, it's just a hack to get them to accept an array of arguments, since the native API only specifies a list of variables. .apply() can accept arrays of arguments, which is why it is used.

我的猜测是 Math 作为 this 参数传入只是为了清洁.

My guess is Math is passed in as the this argument simply for cleanliness' sake.

感谢@Jonathan Lonowski 和@Niet the Dark Absol.

Thanks to @Jonathan Lonowski and @Niet the Dark Absol.

这篇关于.apply(Math, arrayName) 如何工作?(javascript)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆