JavaScript 中的 this指向

本文详细探讨了JavaScript中this的指向,包括直接调用、全局函数、构造函数、对象方法、new关键字、call和apply方法、定时器、事件绑定等多种情况下的this指向,帮助理解JavaScript中的上下文环境。

1、直接调用,指向全局

console.log(this);  // window

在这里插入图片描述

2、全局函数中的this

  • 在普通函数里调用,指向全局
function fn(){
    console.log(this);
}
fn();

在这里插入图片描述

  • 在严格模式下,this 是undefined
function demo(){
	'use strict';
	console.log(this);   // undefined
}
demo();

在这里插入图片描述


3、构造函数普通调用,指向全局(构造函数也是普通函数,可以正常执行)

function Car(){
	this.name="奥迪";
	console.log(this);
}
Car();

在这里插入图片描述


4、构造函数通过new调用创建一个实例对象,指向这个实例对象

var x = 0;
function Student(name,x){
	this.name=name;
	this.x=x;
	console.log(this.x)
}
var zhangsna=new Student("zhangsan",1);
var lisi=new Student("lisi",2);

在这里插入图片描述


5、对象(json创建)里面的方法调用,指向这个对象

var object1={
	name:"zhangsan",
	show:function(){
		console.log(this);
	}
}
object1.show();

在这里插入图片描述


6、对象(通过Object创建)里面的方法调用,指向这个对象

var object2 = new Object();
object2.name='zhangsan';
object2.show=function(){
    console.log(this);
}
object2.show();

在这里插入图片描述


7、对象(通构造函数创建)里面的方法调用,指向这个对象

function Student(){
	this.name="zhangsan"
	this.show=function(){
		console.log(this);
	}
}
var object3 = new Student();
object3.show();

在这里插入图片描述


8、函数调用的时候,前面加上 new 关键字

所谓构造函数,就是通过这个函数生成一个新对象,这时,this就指向这个对象

function demo(){
	//alert(this);   //this ->object
	this.testStr='this is a test';
}
let a = new demo();
console.log(a.testStr); // 'this is a test'

在这里插入图片描述


9、用call 与 apply 的方式调用函数

function demo(){
	console.log(this);
}
demo.call('abc');  // abc
demo.call(null);  // this -> window
demo.call(undefined);  // this -> window

在这里插入图片描述


10、定时器中的this,指向的是window

setTimeout(function(){
	console.log(this); // this -> window , 严格模式也是指向window
},500)

在这里插入图片描述


11、元素绑定事件,事件触发后,执行的函数中的this,指向的是当前元素

window.onload = function(){
	let $btn = document.getElemnetById('btn');
	$btn.onclick = function(){
		console.log(this); // this -> 当前触发
	}
}

在这里插入图片描述


12、函数调用时如果绑定了bind,那么函数中的this指向了bind中绑定的元素

window.onload = function(){
	let $btn = document.getElementById('btn');
	$btn.addEventListener('click',function(){
		console.log(this);   // window
	}.bind(window))
}

在这里插入图片描述


13、对象中的方法,该方法被哪个对象调用了,那么方法中的 this 就指向该对象

let name = '奥迪'
let obj = {
	name:'迪迦',
	getName:function(){
		console.log(this.name);
	}
}
obj.getName();  // 迪迦
------分隔-------
let fn = obj.getName;
fn();  // 奥迪 this -> window

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值