js中的this指向问题

本文详细介绍了JavaScript中的this关键字在不同场景下的指向,包括全局调用、对象方法、构造函数、箭头函数以及setTimeout和setInterval等上下文中的行为。通过对示例的分析,帮助读者理解this的动态绑定特性及其在函数执行环境中的作用。
摘要由CSDN通过智能技术生成

简述

this 是 JavaScript 语言的一个关键字。它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用
this 的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定 this 到底指向谁
函数的不同使用场合,this 有不同的值。总的来说,this 就是函数运行时所在的环境对象
一、一般的函数调用
一般的函数调用属于全局性调用,因此 this 就代表全局对象 window
let a = 1
function fn() {
	let a = 2
	console.log(this)       // window      this ——> window
	console.log(this.a)     // 1           this ——> window.a  
}
	
fn() 
二、作为对象方法
函数作为某个对象的方法调用,此时 this 指向上级对象
let a = 1
let obj = {
	a: 2,
	fn: function() {
		console.log(this)       // {a: 1, fn: ƒ}    this ——> obj
		console.log(this.a)     // 2                this ——> obj.a
	}
}	

obj.fn()

函数作为某个对象的方法,赋值给一个全局变量,此时 this 指向 window
let  a = 1
let  obj = {
	a: 2,
	fn: function() {
		console.log(this)       // window           this ——> window
		console.log(this.a)     // 1                this ——> window.a
	}
}	

var foo = obj.fn()
foo()

三、构造函数调用
所谓构造函数,就是通过这个函数,可以生成一个新对象。这时,this 就指向这个新对象
function Fn() {
	this.a = 1
	console.log(this)    // Fn {a: 1}     this ——> fn
}

let fn = new Fn()
console.log(fn.a)        // 1

四、箭头函数
箭头函数中没有this 所以不能用作构造函数,否则会报错
let Fn = ()=> {
    console.log(this)
}
let fn = new Fn()  // Fn is not a constructor

五、setTimeout & setInterval
延时函数内部的回调函数的 this 指向全局对象 window
let a = 1
setInterval(function() {
	console.log(this)       // window     this ——> window
	console.log(this.a)     // 1          this ——> window
}, 1000)

setTimeout(function() {
	console.log(this)       // window     this ——> window
	console.log(this.a)     // 1          this ——> window
}, 1000)

六、当this遇到return
如果返回值是一个对象,那么 this 指向的就是那个返回的对象,如果返回值不是一个对象,那么 this 指向函数的实例
function Fn()  
{  
    this.a = 1  
    return {}
}
let fn = new Fn()
console.log(fn.a)     // undefined      this ——> {}

function Fn()  
{  
    this.a = 1  
    return function() {}
}
let  fn = new Fn()
console.log(fn.a)     // undefined      this ——> function() {}

function Fn()  
{  
    this.a = 1  
    return ''
}
let fn = new Fn()
console.log(fn.a)     // 1       this ——> fn

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值