Javascript 中的“this"可以为空吗 [英] Can 'this' ever be null in Javascript

查看:46
本文介绍了Javascript 中的“this"可以为空吗的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似以下的函数:

I have a function along the lines of the following:

    doSomething: function () {
        var parent = null;

        if (this === null) {
            parent = 'some default value';
        } else {
            parent = this.SomeValue();
        }
    }

是否可以将 parent 设置为某个默认值" 或者是否检查 null 是多余的?

Could parent ever be set to 'some default value' or is the check for null superfluous?

或者,如果我使用限制较少的会怎样:

Alternatively, what if I used the less restrictive:

    doSomething: function () {
        var parent = this ? this.SomeValue() : 'some default value';
    }

在这种情况下,是否可以将 parent 设置为某个默认值"?

推荐答案

在非严格模式下,this 经历了一个 Object(this) 转换,所以它总是说实话.例外是 nullundefined,它们映射到全局对象.所以 this 永远不是 null 并且总是真实的,这使得两个检查都是多余的.

In non-strict mode, this has undergone an Object(this) transformation, so it's always truthy. The exceptions are null and undefined which map to the global object. So this is never null and always truthy, making both checks superfluous.

然而,在严格模式下,this 可以是任何东西,所以在这种情况下你必须小心.但话又说回来,您必须自己选择严格模式,因此如果您不这样做,则无需担心.

In strict mode, however, this can be anything so in that case you'd have to watch out. But then again you have to opt in for strict mode yourself, so if you don't do that there are no worries.

(function() {               return this; }).call(null); // global object
(function() { "use strict"; return this; }).call(null); // null

ES5 的规范说:

thisArg 值作为 this 值被不加修改地传递.这是对版本 3 的更改,其中未定义或空的 thisArg 被替换为全局对象,并且 ToObject 应用于所有其他值,并且该结果作为 this 传递价值.

The thisArg value is passed without modification as the this value. This is a change from Edition 3, where a undefined or null thisArg is replaced with the global object and ToObject is applied to all other values and that result is passed as the this value.

这篇关于Javascript 中的“this"可以为空吗的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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