如果JavaScript具有一流函数,为什么不在变量中调用此函数呢? [英] If JavaScript has first-class functions, why doesn’t calling this function in a variable work?

查看:78
本文介绍了如果JavaScript具有一流函数,为什么不在变量中调用此函数呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript声称具有一流的功能,因此以下情况似乎应该有效:

JavaScript is purported to have first-class functions, so this seems like the following ought to work:

var f = document.getElementById;
var x = f('x');

但它在所有浏览器上都失败,每个浏览器都有不同的神秘错误消息。 Safari说类型错误。 Chrome说非法调用。 Firefox说无法转换JavaScript参数。

But it fails on all browsers, with a different cryptic error message on each one. Safari says "Type error". Chrome says "Illegal invocation". Firefox says "Could not convert JavaScript argument".

为什么?

推荐答案

因为在JavaScript函数中绑定到上下文( this )。您可以使用 bind()

Because in JavaScript functions arent bound to context (this). You may use bind():

var f = document.getElementById.bind(document);

这篇关于如果JavaScript具有一流函数,为什么不在变量中调用此函数呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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