gpt4 book ai didi

javascript - if(this) {} else {} 是否曾经访问过 JavaScript 中的 else?

转载 作者:行者123 更新时间:2023-12-05 00:32:27 27 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How does the "this" keyword work, and when should it be used?

(22 个回答)


6 个月前关闭。




有没有条件if(this) {}失败?因为我想不出 this 的场景是未定义的。
这不是一个重要的问题,也不是任何人通常会使用的问题,我只是出于好奇而问。

最佳答案

是的,在某些执行上下文中,thisundefined ,即 falsy在 JavaScript 中:

In strict mode, however, if the value of this is not set when entering an execution context, it remains as undefined, as shown in the following example:


这是至少一个复杂的场景,其中必须满足以下条件:
  • strict mode 中的全局或函数执行
  • 该函数在顶层定义(实际上是 window 的函数)
  • 该函数被直接调用而不调用其父函数(即 foo() 而不是 window.foo() )
  • 函数返回 this
  • function foo() {
    'use strict'; // see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
    return this;
    }
    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

    关于javascript - if(this) {} else {} 是否曾经访问过 JavaScript 中的 else?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71082770/

    27 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com