【问题标题】:If a strict mode function is executed using function invocation, its 'this' value will be undefined如果使用函数调用执行严格模式函数,则其 'this' 值将未定义
【发布时间】:2018-09-27 17:14:48
【问题描述】:

我在使用 jshint 时收到以下警告。 为什么?

如果使用函数调用来执行严格模式的函数,它的 'this' 值将是未定义的。

function demo() {
    'use strict';

    document.querySelector('#demo').addEventListener('click', test);

    function test() {
        console.log(this);
    }
}

【问题讨论】:

  • 因为如果您调用test 而不使用某种方式提供明确的thisArgthis 确实会是undefined。所以test() 会给你undefinedthis 值。
  • 您需要使用.call().apply()this 传递给通过间接调用调用的函数。我不知道为什么严格模式会这样做,但确实如此。
  • 如果您尝试将this 用作对象(例如尝试访问属性),则会导致问题。在所写的特定功能中不是问题。没有严格模式,你肯定是一个对象。
  • 我想我必须配置 jsHint 以不触发这些警告?
  • 是的,这一切都是可配置的。 jshint.com/docs/options/#validthis

标签: javascript jshint


【解决方案1】:

这对我有用

function demo() {
  'use strict';

  var that = this; //new line

  document.querySelector('#demo').addEventListener('click', test);

  function test() {
    console.log(that); //print that instead of this
  }
}

【讨论】:

    【解决方案2】:

    与其试图抑制警告,不如解决根本原因。

    this 的使用可能会造成混淆,重构代码时this 的值可能会意外更改。如果您显式传递参数,您的代码将更易于阅读和维护。

    传递给test()回调的参数是点击Event对象:

    function demo() {
       'use strict';
       function test(event) {
          console.log('You clicked on:', event.target.outerHTML); 
          }
       document.querySelector('#demo').addEventListener('click', test);
       }
    
    demo();
    

    控制台日志输出类似于:
    You clicked on: <h1 id="demo">Click Me</h1>

    Event 对象告诉您用户点击的目标元素:
    https://developer.mozilla.org/en-US/docs/Web/API/Event/target


    拨弄代码:
    https://jsfiddle.net/24epdxbz/2

    来自yehudakatz

    ECMAScript 5 规范说 undefined (几乎)总是被传递,但是当不处于严格模式时,被调用的函数应该将其 thisValue 更改为全局对象。这允许严格模式调用者避免破坏现有的非严格模式库。

    【讨论】:

      【解决方案3】:

      根据 Scope in js 之类的文章,有时 JS 中的范围需要它而不是这个,

      因此,您通常需要使用

      var that = this;
      

      【讨论】:

        猜你喜欢
        • 2023-03-24
        • 2013-10-08
        • 1970-01-01
        • 2017-10-31
        • 2018-08-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多