如果使用函数调用执行严格模式函数,其 'this' 值将未定义
If a strict mode function is executed using function invocation, its 'this' value will be undefined
我在使用 jshint 时收到以下警告。
为什么?
If a strict mode function is executed using function invocation, its 'this' value will be undefined.
function demo() {
'use strict';
document.querySelector('#demo').addEventListener('click', test);
function test() {
console.log(this);
}
}
与其试图抑制警告,不如解决根本原因。
this
的使用可能会造成混淆,并且在重构代码时 this
的值可能会意外更改。如果您显式传递参数,您的代码将更易于阅读和维护。
传递给 test()
回调的参数是 click 的 Event
对象:
function demo() {
'use strict';
function test(event) {
console.log('You clicked on:', event.target.outerHTML);
}
document.querySelector('#demo').addEventListener('click', test);
}
demo();
控制台日志输出类似于:
You clicked on: <h1 id="demo">Click Me</h1>
Event
对象告诉您用户点击的目标元素:
https://developer.mozilla.org/en-US/docs/Web/API/Event/target
Fiddle 代码:
https://jsfiddle.net/24epdxbz/2
来自 yehudakatz:
The ECMAScript 5 spec says that undefined
is (almost) always passed, but that the function being called should change its thisValue
to the global object when not in strict mode. This allows strict mode callers to avoid breaking existing non-strict-mode libraries.
这对我有用
function demo() {
'use strict';
var that = this; //new line
document.querySelector('#demo').addEventListener('click', test);
function test() {
console.log(that); //print that instead of this
}
}
根据这样的文章,有时 JS 中的范围需要那个而不是这个 Scope in js
因此,您通常需要使用
var that = this;
我在使用 jshint 时收到以下警告。 为什么?
If a strict mode function is executed using function invocation, its 'this' value will be undefined.
function demo() {
'use strict';
document.querySelector('#demo').addEventListener('click', test);
function test() {
console.log(this);
}
}
与其试图抑制警告,不如解决根本原因。
this
的使用可能会造成混淆,并且在重构代码时 this
的值可能会意外更改。如果您显式传递参数,您的代码将更易于阅读和维护。
传递给 test()
回调的参数是 click 的 Event
对象:
function demo() {
'use strict';
function test(event) {
console.log('You clicked on:', event.target.outerHTML);
}
document.querySelector('#demo').addEventListener('click', test);
}
demo();
控制台日志输出类似于:
You clicked on: <h1 id="demo">Click Me</h1>
Event
对象告诉您用户点击的目标元素:
https://developer.mozilla.org/en-US/docs/Web/API/Event/target
Fiddle 代码:
https://jsfiddle.net/24epdxbz/2
来自 yehudakatz:
The ECMAScript 5 spec says that
undefined
is (almost) always passed, but that the function being called should change itsthisValue
to the global object when not in strict mode. This allows strict mode callers to avoid breaking existing non-strict-mode libraries.
这对我有用
function demo() {
'use strict';
var that = this; //new line
document.querySelector('#demo').addEventListener('click', test);
function test() {
console.log(that); //print that instead of this
}
}
根据这样的文章,有时 JS 中的范围需要那个而不是这个 Scope in js
因此,您通常需要使用
var that = this;