03-this指向

1、全局环境输出this,指向Window。

<script>
	console.log(this); //Window
</script>

2、全局函数输出this,指向Window。

原理:全局函数其实是window(全局对象)的方法。

function fun() {
	console.log(this); //Window
}
fun(); // 是 Window.fun() 的简写

3、对象的方法输出this,指向调用者。

let cat = {
	name: '喵喵',
	sayName() {
		console.log('我是' + this.name);
	}
}
cat.sayName(); //我是喵喵

4、DOM事件输出this,指向触发事件的DOM对象。

<button>按钮</button>
<script>
	const btn = document.querySelector('button');
	btn.onclick = function() {
		console.log(this); //<button>按钮</button>
	}
</script>

5、构造函数中的this,指向实例,也就是new创建的对象。

构造函数:是用来创建对象的

构造函数和普通函数一样,可以直接调用的,没有new之前指向Window

function Fun() {
	console.log(this); //Window 
}
Fun();

在构造函数调用前加new关键字,代表创建实例对象。

此时this指向f,f是一个空对象

function Fun() {
	console.log(this); //Fun {}
}
let f = new Fun();
console.log(f); //Fun {}

6、new关键字做了什么?

new会创建对象,将构造函数的this指向创建出来的对象

function Fun() {
	this.name = '小米'
}
let f = new Fun();
console.log(f); //Fun {name: '小米'}

7、箭头函数中的this,指向它的父级。

计时器包裹普通函数,this指向Window。

let cat = {
	name: '喵喵',
	sayName() {
		setTimeout(function() {
			console.log(this);
		}, 100);
	}
}
cat.sayName(); //Window 

计时器包裹箭头函数,this指向其外层函数。

let cat = {
	name: '喵喵',
	sayName() {
		setTimeout(() => {
			console.log(this);
		}, 100);
	}
}
cat.sayName(); //{name: '喵喵', sayName: ƒ}

准确来说,箭头函数没有this

  • 普通函数,谁调用指向谁;箭头函数,在哪里定义指向谁;
  • 箭头函数外指向谁就指向谁;

猜你喜欢

转载自blog.csdn.net/iaz999/article/details/131240375
03