杰辛特 |传递默认设置 |函数声明和“this”
Jshint | Passing default settings | Function declarations and 'this'
for ( element = 0; element < this.tag_array.length; element++ ) {
document.getElementById( this.tag_array[element] ).addEventListener(
"click", function(){ /* constructor function here */ } ); // jshint.com error #1
}
此代码将导致 bc jshint.com 错误,它不希望看到在循环中声明的函数。
但是,如果我传入一个简单的函数引用,那么我无法在不再次破坏 jhint 的情况下提取出"this"。
for ( element = 0; element < this.tag_array.length; element++ ) {
document.getElementById( this.tag_array[element] ).addEventListener(
"click", vFlipBP );
}
现在,当我在vFlipBP中使用"this"时,我收到一个错误b.c.它期望"this"与构造函数结合使用。
function vFlipBP(){ var foo = this ; } // jshint error #2
正因为如此,我发现不可能让 jsthint.com 在这个特定的功能中感到高兴。
没关系关闭 jshint.com 选项。
是否可以编写传递 jshint.com 默认设置的代码。
我只是想了解它为什么发出这些警告/错误的原因。
我不会担心错误(这是可选的,我可以将其关闭)...我只想知道是否有可能通过默认值...有没有我错过的角度。
由于您似乎并不关心制作几个相同的函数,因此 JSHint 似乎并不介意这一点......
var element;
for ( element = 0; element < 10; element++ ) {
document.getElementById( this.tag_array[element] ).addEventListener(
"click", make_func() );
}
function make_func() {
"use strict";
return function(){ var foo = this; alert(foo); };
}
如果您不使用函数声明语法,它似乎也可以接受......
var element;
var the_func = function(){
"use strict";
var foo = this;
alert(foo);
};
for ( element = 0; element < 10; element++ ) {
document.getElementById( this.tag_array[element] ).addEventListener(
"click", the_func );
}
看起来您想在回调中使用this
作为上下文,但 jshint 抱怨在不是构造函数的函数中使用它。
所以假设这是你拥有的代码
function showId() {
alert(this.id); // jshint warning here
}
for ( element = 0; element < this.tag_array.length; element++ ) {
document.getElementById( this.tag_array[element] ).addEventListener(
"click", showId );
}
你必须重写你的函数,这样它就不会使用this
,这是一种可能的方法
function createHandler(obj) {
return function(e) {
alert(obj.id);
}
}
for ( element = 0; element < this.tag_array.length; element++ ) {
var nodeId = this.tag_array[element];
var node = document.getElementById(nodeId);
node.addEventListener("click", createHandler(node));
}
你不能告诉jshint这个特定的功能可以安全使用this
吗?有了这个选项validthis
?在Google闭包编译器中,您可以使用@this
指定您知道该函数中将包含哪些this
(并避免警告)https://developers.google.com/closure/compiler/docs/js-for-compiler
相关文章:
- Eval未声明函数
- JavaScript + mocha:可能是在 for 循环中声明函数的闭包问题
- 使用 .on 函数运行 jQuery 声明函数
- 返回并重新声明函数中的变量
- SyntaxError:严格模式不允许在词法嵌套语句中声明函数
- JavaScript函数的类型是在声明函数之前定义的
- 在 initComponent Ext JS4 中声明函数
- 在对象中声明函数名称,为什么
- 在变量中声明函数的不同方法
- 声明函数是否会创建具有函数名称和分配给它的函数对象的变量
- 在 angularjs 控制器范围内声明函数和属性,但不附加到$scope
- 在声明函数中使用“this”时严格违规,函数表达式不违规
- 只有从html set onclick事件调用代码声明函数时,该函数才不存在
- 在jQuery中动态声明函数
- 声明函数并在jquery事件绑定上调用它
- 在Javascript中声明函数的最有效方法是什么
- javascript声明函数超时
- Javascript:动态声明函数的正确方法
- 为闭包声明函数两次
- 习语Javascript编码风格-何时在原型上声明函数,何时在函数构造函数内声明函数