【问题标题】:Resolve possible strict violation (and help Batman save Gotham) [duplicate]解决可能的严格违规问题(并帮助蝙蝠侠拯救哥谭)[重复]
【发布时间】:2015-03-15 19:44:55
【问题描述】:

我有以下(简化的)Batman.js 文件:

(function(){
  "use strict";

  window.Batman = function(){
    // Global references
    this.version = "1.0.1";
  };

  Batman.prototype.saveGotham = function(params) {
    var _ = this; // Works fine
    destroyGotham.call(_, params);
  };

  // Private
  function destroyGotham(params){
    var _ = this; // <!-- "possible strict violation"
  }

}());

JSHint 在指定行抱怨possible strict violation。如何在不删除 "use strict" 的情况下解决此问题?

P.S:我希望麻烦的 var _ = this 引用 Batman 实例。

【问题讨论】:

    标签: javascript strict iife


    【解决方案1】:

    作为this 传递给严格模式下的函数的值不会被强制为对象。
    对于普通函数,this 始终是一个对象,如果使用未定义或空的this 调用它是全局对象,换句话说,this 通常在非严格模式下默认为window

    自动装箱不仅会降低性能成本,而且在浏览器中公开全局对象也会带来安全隐患,因为全局对象提供了对“安全”JavaScript 环境必须限制的功能的访问。
    因此对于严格模式函数,指定的this 不会被装箱到对象中,如果未指定,this 将默认未定义。

    这意味着这样使用this,只需将其设置为变量

    var _ = this;
    

    在大多数情况下会导致 this 未定义,这就是为什么 jshint 说这是一个“可能” 违规,因为如果您没有使用 call 和提供了一个 this 值。

    忽略 jshint,你做的很好。

    【讨论】:

    • 我该如何解决?
    • 您在调用函数时忽略了 jshint,而this 将被定义,
    • 谢谢 -- 我发现您可以在抱怨的var _ = this; 上方的行中添加/*jshint validthis:true */ 以抑制错误。
    • 是的,如果你只需要通过 jshint,你可以跳过this 测试
    • 或者,将 "validthis": "_" 添加到您的 jshint 配置中
    猜你喜欢
    • 2017-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-10
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多