2017-07-18 31 views
0

我正在優化我的用戶與JSlint的代碼,我來到一個小問題,我試圖找到解決方案。在下面的代碼中,JSlint抱怨.bind(this)。如果我刪除.bind(this),那麼代碼不知道什麼是「this.selectorCache.get()」和「this.someFunc()」。JSLint不喜歡.bind(this),但沒有它,this.obj無法訪問

有沒有辦法通過刪除.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)); 
+0

這是由於PhantomJS。 https://www.npmjs.com/package/phantomjs-polyfill https://stackoverflow.com/questions/27659514/phantomjs-function-prototype-bind – evolutionxbox

+1

jslint的實際錯誤是什麼? –

+0

當我通過jslint運行你的代碼時,我得到很多評論,但與綁定無關,所以,這是什麼問題? – James

回答

2

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

抱怨「嚴格使用」;特別是在(。)部分。我會測試它,並會讓你知道。 –

+0

無法使用const,因爲它是es6,儘管var _this = this;訣竅。 –

0

解決方案@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()); 
     } 
    }; 
    }); 
}); 
+0

有趣的是,雖然我的應用程序在es5中。 –