在Javascript中将函数应用于Null [英] Applying a Function to Null in Javascript

查看:172
本文介绍了在Javascript中将函数应用于Null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么以下工作:

function sum(a,b) { return a + b; }
var result = sum.call(null,3,4);     // 7

为什么要定义结果?我正在调用sum作为null的方法。但是null不是一个对象而且不能有属性!

Why is result defined? I am invoking sum as a method of null. But null is not an object and cannot have properties!

发生了什么?

推荐答案

Function.prototype.call 的第一个参数是 context ,它定义 this 被调用函数的执行上下文的值,没有别的。

The first argument for Function.prototype.call is the context, which defines the this value for the execution context of the invoked function, nothing else.

所以基本上,你说这个指的是 null (至少在ES5严格模式下),但由于你没有访问这个无论如何,它没有区别。

So basically, you're saying that this is referring to null (at least, in ES5 strict mode), but since you don't access this anyway, it makes no difference.

在非严格模式下,不能 null ,因此它被替换为全局对象

In non-strict mode, this cannot be null, so it's replaced with the global object instead.

这篇关于在Javascript中将函数应用于Null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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