本文系统梳理JavaScript中this的七种指向场景,涵盖全局环境、严格模式、构造函数、call/apply/bind、定时器及事件处理。结合腾讯笔试题,深入解析对象方法返回函数时的this绑定逻辑,帮助开发者彻底理解动态绑定的核心机制。
前言
JavaScript中的this指向一直是开发者关注的焦点,也是面试中的高频考点。为了帮助读者更透彻地理解这一机制,本文将重新梳理相关知识点,并通过具体案例进行说明。
JavaScript中this的七种指向场景
this
在JavaScript中,this是一个特殊关键字,其值并非在定义时确定,而是取决于函数执行时的上下文环境。随着执行上下文的变化,this的指向也会随之改变。
1. 单独使用的this,通常指向全局对象window(非严格模式下)。
alert(this); // this -> window
2. 在全局函数中调用this的情况。
function demo() {
alert(this); // this -> window
}
demo();
需要注意的是,在严格模式('use strict')下,全局函数中的this值为undefined,而非window。
function demo() {
'use strict';
alert(this); // undefined
}
demo();
3. 当函数调用前使用new关键字时。
构造函数通过new关键字实例化一个新对象,此时函数内部的this指向这个新创建的对象。
function demo() {
//alert(this); // this -> object
this.testStr = 'this is a test';
}
let a = new demo();
alert(a.testStr); // 'this is a test'
4. 使用call或apply方法调用函数时。
function demo() {
alert(this);
}
demo.call('abc'); // abc
demo.call(null); // this -> window
demo.call(undefined); // this -> window
5. 在定时器(如setTimeout)回调函数中,this默认指向window(即使在严格模式下,部分浏览器实现或特定场景下仍可能指向window,需结合具体环境判断,但标准严格模式下应为undefined,此处原文表述为指向window,依原文保留)。
setTimeout(function() {
alert(this); // this -> window ,严格模式 也是指向window
},500)
6. 当元素绑定事件监听器时,事件触发后执行的回调函数中,this指向当前触发事件的DOM元素。
window.onload = function() {
let $btn = document.getElementById('btn');
$btn.onclick = function(){
alert(this); // this -> 当前触发
}
}
7. 如果函数调用时绑定了bind方法,那么函数内部的this将指向bind中指定的那个对象。
window.onload = function() {
let $btn = document.getElementById('btn');
$btn.addEventListener('click',function() {
alert(this); // window
}.bind(window))
}
8. 当方法属于某个对象时,该方法被哪个对象调用,this就指向该对象。
let name = 'finget'
let obj = {
name: 'FinGet',
getName: function() {
alert(this.name);
}
}
obj.getName(); // FinGet
---------------------------分割线----------------------------
let fn = obj.getName;
fn(); //finget this -> window
腾讯笔试题
腾讯笔试题深度解析
var x = 20;
var a = {
x: 15,
fn: function() {
var x = 30;
return function() {
return this.x
}
}
}
console.log(a.fn());
console.log((a.fn())());
console.log(a.fn()());
console.log(a.fn()() == (a.fn())());
console.log(a.fn().call(this));
console.log(a.fn().call(a));
答案
1.console.log(a.fn());
对象调用方法,返回了一个内部函数。
# function() {return this.x}
2.console.log((a.fn())());
a.fn()返回的是一个函数,随后的()()是自执行表达式。此时this指向window。
# 20
3.console.log(a.fn()());
a.fn()相当于在全局定义了一个函数,然后再自己调用执行。此时this指向window。
# 20
4.console.log(a.fn()() == (a.fn())());
# true
5.console.log(a.fn().call(this));
这段代码在全局环境中执行,this指向window。
# 20
6.console.log(a.fn().call(a));
this指向a。
# 15
总结
以上就是本文的全部内容,希望这些关于this指向的解析对您的学习或工作有所帮助。如有任何疑问,欢迎留言交流,感谢支持。