在Javascript中,'this'可以为null [英] Can 'this' ever be null in Javascript

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

问题描述

我的功能如下:

    doSomething: function () {
        var parent = null;

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

父母可以设置为'某些默认值'或检查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';
    }

父级是否可以设置为某个默认值 case?

推荐答案

在非严格模式下,已经经历了对象(此)转换,因此它始终是真实的。例外是 null undefined 映射到全局对象。所以这个永远不会 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.

但是,在严格模式下,这个可以是任何东西,所以在这种情况下你必须要小心。但是你必须自己选择严格模式,所以如果你不这样做就没有后顾之忧。

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

规范说:


传递thisArg值没有修改作为此值。这是对第3版的更改,其中未定义或null thisArg替换为全局对象 ToObject 应用于所有其他值,结果将作为此传递价值。

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'可以为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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