本文介绍了为什么我不能在箭头函数中省略getElementById()的参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在页面上有3个< img> 标记,我想将这些标记作为数组,所以我写道:

Say I have 3 <img> tags on a page, and I would like to get these as an array, so I wrote:

让myArray = ['img1','img2','img3']。map(id => document.getElementById(id));

...运作良好。

然后我想,嘿, getElementById 只需1个参数。是不是有语法糖?所以我写道:

Then I thought, hey, getElementById takes exactly 1 argument. Isn't there a syntax sugar for that? So I wrote:

让myArray = ['img1','img2','img3']。map(document.getElementById);

......但这不起作用。我在Chrome上收到了非法调用。

... but that didn't work. I got "Illegal invocation" on Chrome.

所以它不是语法糖。所有这些背后的原因是什么?

So it's not syntax sugar then. What's behind all these?

推荐答案

JavaScript在方法调用和函数调用之间存在差异。前者将设置为,后者则不会。从语法上讲,方法调用必须是 receiver.method(... args)。没有点,没有方法调用。所以,这个:

JavaScript has a difference between "method call" and "function call". The former will set this, the latter won't. Syntactically, method call must be of form receiver.method(...args). No dot, no method call. So, this:

document.getElementById(id) // method call, `this` is set to `document`
m = document.getElementById; m(id) // function call, `this` is not set

当你执行<$ c时$ c> map(document.getElementById), document.getElementById 是从其对象中提取的函数;当 map 调用它时,它将在没有接收器的情况下调用它,这个将不会被设置,并且事情变得糟糕。

When you do map(document.getElementById), document.getElementById is a function plucked from its object; when map invokes it, it will invoke it without the receiver, this will not be set, and things get bad.

有一种方法可以保存它: bind ,它通过将接收器绑定到它来方法化一个函数: map(document.getElementById.bind(document))应该可以工作。

There is a way to save it: bind, which "methodifies" a function by binding a receiver to it: map(document.getElementById.bind(document)) should work.

编辑:进一步说明:

let foo = {
  bar: function(context) {
    let receiver =
      (this == window) ? "window" :
      (this == foo) ? "foo" :
      "unknown";
    console.log(context + ", `this` is `" + receiver + "`");
  }
}

function call(fn, param) {
  fn(param);
}

foo.bar("In direct call");
let baz = foo.bar; baz("When assigned to a variable");
call(foo.bar, "When passed as a parameter")
let quux = foo.bar.bind(foo); quux("When bound to foo");

这篇关于为什么我不能在箭头函数中省略getElementById()的参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:27