JSLint 不喜欢 .bind(this),但没有它,this.obj 无法访问

JSLint does not like .bind(this), but without it, this.obj cannot be accessed

我正在使用 JSlint 为用户优化我的代码,我遇到了一个小问题,我正在尝试找到解决方案。在下面有效的代码中,JSlint 抱怨 .bind(this)。如果我删除 .bind(this),则代码不知道什么是 "this.selectorCache.get()" 或 "this.someFunc()"。

有没有办法通过删除 .bind(this) 来使此代码正常工作?

/*jslint this:true, devel: true */
/*global jQuery, $, window, SelectorCache */
"use strict";

$(function () {
    window.myApp = (function () {
        var _this = this;
        this.selectorCache = new SelectorCache();// selector cache function

        this.someFunc = function () {
            return 0;
        };

        this.selectorCache.get('#someID').click(function () {
            if (_this.this.selectorCache.get('#someOtherID').val() === 1){
                console.log(_this.someFunc());
            }
        }.bind(this));
    }.bind(this));
}.bind(this));

this 上下文存储到另一个变量并在回调中使用它。

不过,我建议您使用 bind(this) 并找出 JSLint 抱怨的确切原因。

window.myApp = (function () {
    var _this = this;

    this.selectorCache = new selectorCache();// selector cache function

    this.someFunc = function () {
        return 0;
    }

    this.selectorCache.get('#someID').click(function () {
        if _this.selectorCache.get('#someOtherID').val() === 1{
            console.log(_this.someFunc());
        }
    });
}

@Erazhihel 提出的解决方案应该可以解决问题。另一种最简单的修复方法是改用 ES6 的箭头函数。

/* global jQuery, $, window */
"use strict";

$(function() {
  window.myApp = (function () {

    this.selectorCache = new selectorCache();// selector cache function

    this.someFunc = function (){
        return 0;
    }

    this.selectorCache.get('#someID').click(() => {
      if (this.selectorCache.get('#someOtherID').val() === 1){
        console.log(this.someFunc());
      }
    };
  });
});