JAVASCRIPT编程 this的用法

本文深入探讨JavaScript中this关键字的指向问题,通过具体示例代码解释不同情况下this的实际指向对象,并对比直接调用与通过回调函数调用的区别。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一段代码:

 

<script>
	function A(){
		this.nameA = null;
		this.fun=null;
		
		this.init = function(){
			this.nameA="xxxyyyyyzzzz";
		};
		this.init();
		
	}
	
	function B(){
		this.a =null;
		this.init = function(){
			var _a = new A();
			_a.fun = this.callbackFun;
			this.a=_a;
		};
		
		//第一种方式 直接调用
		this.callA = function(){
			alert(this.a.nameA);
		};
		//第二种方式 回调
		this.callbackA = function(){
			this.a.fun();
		};
		this.callbackFun = function(){
			alert(this.nameA);
			//alert(this.a.nameA); //错误
		};
		
		this.init();
	}
	
	var b = new B();
	b.callA();
	b.callbackA();
	
	
	</script>

问题:this到底指向谁?

答案:this指向调用函数的对象。谁调用函数,函数中的this就指向谁

function fun(){

     this.name="";   //不管函数定义在那个类中,函数中的this只会关心调用他的对象

}

调用函数时this的指向:

fun(),//this指向window

a.fun();//this指向a

a.b.fun(),//this指向b


 

例子的第二种方式,通过回调输出a对象的nameA属性时,alert(this.a.nameA);是错误的,alert(this.nameA);才是对的,原因就是this指向了a,而不是b了
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值