2016-09-25 50 views
0

jslint不喜歡this如何傳遞jslint並將全局變量傳遞給我的IIFE?

}(this)); 

但它是如何將全局變量傳遞給在客戶端和服務器上運行的我的IIFE。

我該如何改變它?

我想通過沒有選項設置的jslint。

+0

只需在行尾添加'// jshint ignore:line'? – ivarni

+0

找到[更好的棉絨](http://eslint.org)。 – 2016-09-25 17:58:10

回答

1

它需要通過相當數量的箍跳,但你可以定義此功能,它通過JSLint的,並返回到全局對象的引用:

function getGlobal() { 
    // just creating a function here so that we can get at the Function constructor 
    // via noop.constructor 
    var noop = function() { 
     // dummy statements so the linter doesn't complain about an 
     // empty block or unused variables 
     var a = null; 
     return a; 
    }; 

    return noop.constructor("return this")(); 
} 

注意,這個功能本身需要在全球範圍內定義。您可以定義它並在您的IIFE中調用它。

+0

你知道我偶然得到的「錯誤」背後的推理嗎? –

+0

@mikeyballs Douglas Crockford不鼓勵使用'this',因爲它是不可預測的,可能會暴露安全漏洞。他至少在一次談話中談到過這個問題,可能更多。我找不到一個,但是這裏有其他人在談論爲什麼要避免'this':https://nemisj.com/js-without-new-and-this/ – JLRishe

+0

所以有一些JavaScript編程風格,不要使用'this'? –