JavaScript函数上下文不正确 [英] JavaScript Function Context Incorrect

查看:132
本文介绍了JavaScript函数上下文不正确的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我注意到javascript中有一个奇怪的东西。请考虑以下内容:

I noticed a weird thing in javascript. Consider the below:

var fn = ''.toUpperCase.call
console.log(typeof fn); // "function"
fn(); // Uncaught TypeError: `fn` is not a function

以上是在我的Chrome开发者控制台上执行的。版本 43.0.2357.81 m

The above was executed on my Chrome's Developer Console. Version is 43.0.2357.81 m.

typeof 运算符清楚地显示 fn 是一个函数,但错误暗示不然。

The typeof operator clearly shows that fn is a function, but the error suggests otherwise.

我注意到 Function.apply 显示至少一些有意义的错误消息。

I've noticed that Function.apply shows at least some meaningful error message.

那么,什么时候是函数,而不是函数?

So, when is a function, not a function?

推荐答案

Javascript中的上下文总是通过调用函数的方式建立。

Context in Javascript is always established by the way you call a function.

var fn = ''.toUpperCase.call

这将调用函数的原型实现分配给 fn 。如果您现在调用 fn(),则该调用没有上下文。 call 会尝试调用与之关联的函数对象。但是,该上下文是在呼叫时建立的。由于您在通话时没有给出任何上下文,调用的某些内部组件会抛出错误。

This assigns the prototype implementation of the call function to fn. If you now call fn(), there's no context to the call. call would try to invoke the function object it was associated with. However, that context is established at call time. Since you're not giving it any context at call time, some internal component of call is throwing an error.

你必须这样做:

fn.call(''.toUpperCase)

这是正确的,您致电 致电 function,建立一个上下文,即 toUpperCase 字符串函数。在这种特定情况下,这将导致 toUpperCase 内的另一个错误,因为 it 未绑定到特定上下文。您还需要明确地建立该上下文:

That's right, you call the call function, establishing a context, namely the toUpperCase string function. In this specific case this would lead to another error inside toUpperCase, since it is not bound to a specific context. You'd need to establish that context explicitly as well:

var fn = ''.toUpperCase.call
fn.call(''.toUpperCase.bind(''))

另见这个怎么样?关键字工作?

这篇关于JavaScript函数上下文不正确的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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