请说说严格模式下的this指向
在JavaScript中,this的指向取决于函数如何被调用,而不是函数如何被定义。在严格模式('use strict';)下,this的指向有一些特殊规则。
- 全局作用域或者函数外的
this:在非严格模式下,全局作用域或者函数外的this指向全局对象(在浏览器中是window)。但在严格模式下,this是undefined。
'use strict';
console.log(this); // undefined
- 构造函数中的
this:在构造函数中,无论是严格模式还是非严格模式,this都指向新创建的对象实例。
'use strict';
function MyConstructor() {
this.value = 'Hello, World!';
}
var instance = new MyConstructor();
console.log(instance.value); // 'Hello, World!'
- 对象方法中的
this:在对象的方法中,this指向调用该方法的对象。这一点在严格模式和非严格模式下都是一致的。
'use strict';
var obj = {
value: 'Hello, World!',
printValue: function() {
console.log(this.value);
}
};
obj.printValue(); // 'Hello, World!'
- 事件处理器中的
this:在事件处理器中,this通常指向触发事件的元素。这一点在严格模式和非严格模式下都是一致的。
'use strict';
var button = document.querySelector('button');
button.addEventListener('click', function() {
console.log(this); // 指向button元素
});
- 普通函数调用中的
this:在严格模式下,普通函数调用中的this是undefined,而在非严格模式下,它指向全局对象(在浏览器中是window)。
'use strict';
function myFunction() {
console.log(this); // undefined
}
myFunction();
- call、apply和bind方法:这些方法允许你显式地设置函数运行时
this的值。在严格模式和非严格模式下,它们的行为是一致的。
总的来说,严格模式主要影响了全局作用域或者函数外的this和普通函数调用中的this,使它们从指向全局对象变为undefined。其他情况下,this的指向在严格模式和非严格模式下基本一致。
浙公网安备 33010602011771号