JavaScript 严格模式下 this 指向全解析

作者:闭包旅人时间:2026-10-25 19:57:26浏览:485

本文详细解析 JavaScript 严格模式下 this 的指向规则。涵盖全局作用域、普通函数、对象方法、构造函数、事件处理及定时器等多种场景,对比非严格模式差异,并结合 React 组件特性说明 this 为 undefined 的原因,帮助开发者准确理解并应用严格模式下的 this 行为。

前言

非严格模式下 this 的指向较为常见,而严格模式下的 this 指向相对少见且易混淆。本文将深入剖析严格模式下 this 的具体指向及其在不同场景下的表现,帮助读者彻底理清这一概念。

一、全局作用域中的 this

在严格模式的全局作用域中,this 依然指向 window 对象。

"use strict";
 
console.log("严格模式");
console.log("在全局作用域中的this");
console.log("this.document === document",this.document === document);
console.log("this === window",this === window);
this.a = 9804;
console.log('this.a === window.a===',window.a);

前言

二、全局作用域中函数内的 this

在严格模式下,全局作用域内的普通函数中,this 的值为 undefined。而在非严格模式中,此处 this 指向 window。需要注意的是,在 React 的 render() 方法中,this 指向组件实例对象。务必区分 render() 中的 this 与普通函数中的 this,二者指向不同,因此无法在全局作用域的普通函数中直接通过 this 获取值。

"use strict";
 
console.log("严格模式");
console.log('在全局作用域中函数中的this');
function f1(){
console.log(this);
}
 
function f2(){
function f3(){
console.log(this);
}
f3();
}
f1();
f2();

前言

三、对象方法中的 this

在严格模式下,对象内部函数的 this 指向调用该函数的对象实例。

"use strict";
 
console.log("严格模式");
console.log("在对象的函数中的this");
var o = new Object();
o.a = 'o.a';
o.f5 = function(){
return this.a;
}
console.log(o.f5());

前言

四、构造函数中的 this

在严格模式下,构造函数内部的 this 指向由该构造函数创建的对象实例。

"use strict";
 
console.log("严格模式");
console.log("构造函数中的this");
function constru(){
this.a = 'constru.a';
this.f2 = function(){
console.log(this.b);
return this.a;
}
}
var o2 = new constru();
o2.b = 'o2.b';
console.log(o2.f2());

前言

五、事件处理函数中的 this

在严格模式下,事件处理函数中的 this 指向触发该事件的目标 DOM 对象。

"use strict";
 
function blue_it(e){
if(this === e.target){
this.style.backgroundColor = "#00f";
}
}
var elements = document.getElementsByTagName('*');
for(var i=0 ; i<elements.length ; i++){
elements[i].onclick = blue_it;
}
 
//这段代码的作用是使被单击的元素背景色变为蓝色

六、内联事件处理函数中的 this

在严格模式下,内联事件处理函数中存在两种情况:

<button onclick="alert((function(){'use strict'; return this})());">
内联事件处理1
</button>
<!-- 警告窗口中的字符为undefined -->
 
<button onclick="'use strict'; alert(this.tagName.toLowerCase());">
内联事件处理2
</button>
<!-- 警告窗口中的字符为button -->

七、定时器中的 this

 <script>
        'use strict'
      setTimeout(function(){
        console.log(this);
      },1000)
    </script>
//Window {window: Window, self: Window, document: document, name: '', location: Location, …}

定时器中的 this 指向 window 对象。

注意:严格模式下全局作用域中函数的 this 指向 undefined,这也是 React 函数式组件中 this 为 undefined 的原因。

类中的方法默认开启局部严格模式。

参考资料

MDN https://developer.mozilla.org... 到此结束关于 JS 严格模式下 this 指向的详细讲解,更多相关内容请搜索本站历史文章或浏览后续文章,感谢支持。

作者最新文章