Search code examples
javascriptjquerythisjslint

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


I am optimizing my code for user with JSlint, i came to a small issue that i am trying to find a solution to. In the code below which works, JSlint complains about .bind(this). If i remove .bind(this), then the code does not know what is "this.selectorCache.get()" nor "this.someFunc()".

Is there a way to get this code working by removing .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));

Solution

  • Store the this context to another variable and use it in the callback.

    I'd recommend you to use the bind(this) though and to find out why exactly JSLint complains.

    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());
            }
        });
    }