gpt4 book ai didi

javascript - 使用 "Possible strict violation."时 JSHint `bind`

转载 作者:IT王子 更新时间:2023-10-29 02:49:32 26 4
gpt4 key购买 nike

考虑这个简单的代码:

"use strict";

var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};

function g() {
console.log( this.prop );
}

如果我尝试验证此代码,jshint 会给我错误 Possible strict violation. 我调用 console.log( this.prop ); 的地方。这是因为 this 在函数的严格模式下是未定义的。

但是我在调​​用它之前绑定(bind)了这个函数,所以 this 是正确的对象。

我正在使用这种“设计模式”来避免使主要对象困惑。在参数中传递属性也会使函数变得困惑,所以我拒绝这样做。此外,这正是 bind 的用途。

JSHint 有办法让我这样做吗?

最佳答案

如果不运行代码,很难检测到这种情况。您可以使用选项 validthis 来抑制此警告:

"use strict";

var obj = {
f: function() {
this.prop = 'value';
g.bind( this )();
}
};

function g() {
/*jshint validthis:true */
console.log( this.prop );
}

需要注意的是,jshint 注释是函数作用域的。所以注释将适用于函数 g 及其内部函数,而不仅仅是下一行。

关于javascript - 使用 "Possible strict violation."时 JSHint `bind`,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12057427/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com