JavaScript——this篇

本文详细介绍了JavaScript中函数内部隐含参数this的含义及其值的确定方式。通过实例展示了函数调用的不同方式(直接调用、对象方法调用、构造函数调用、call/apply方法指定调用)对this的影响。同时,提供了多个练习题帮助读者理解并掌握this的指向规律。

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

1.this是什么?

  • this是函数内的一个隐含参数,每个函数内部都有一个参数this。

  • 函数本质上都是通过某个对象来调用的,谁调用该函数,该函数中的this就指向谁。

2.如何确定this的值

  • 概括来讲:谁调用指向谁

  • 调用函数的方式有下面几种:

    test();      ——>this指向window。     这里是把window省去了,可以写为window.test();
    p.test();    ——>this指向p对象。       p调用指向p
    new test();       ——>this指向当前新建的对象。
    test.call(obj);   ——>this指向obj。   call()、apply()方法是指定某个对象来调用该方法。
    

3.练习:确定this指向

<script type="text/javascript">
		function Person(color){
			console.log(this);        //this
			this.color=color;
			this.getColor=function(){
				console.log(this);    //this
				return this.color;
			};
			this.setColor=function(color){
				console.log(this);    //this
				this.color=color;
			};
		}
		Person("red"); 
		//window直接调用,this指向window;
		var p=new Person("yellow");
		// this指向p
		p.getColor();
		// this指向p
		var obj={};
		p.setColor().call(obj,"black");
		// this指向obj;
		var test=p.setColor();
		test();
		//test()得到了一个方法,
		//window调用的test(),所以this指向window;
		function fun(){
			function fun2(){
				console.log(this);
			}
		}
		fun2();
		//this指向window;	
	</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值