前端 - this

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/kelly0721/article/details/102638684

想搞清楚 this 的指向,只需要清楚是谁在调用就好了。

一、四种情况的调用

  1. 直接调用的默认绑定, this 指向一定是全局对象(浏览器的话是 window)。在严格模式下其值会是 undefined。

  2. 对象调用的隐式绑定, this 指向就是这个调用的对象。

  3. call()/apply() 方式的显式绑定, this 指向传入的对象。

  4. new 方式的绑定规则, this 指向这个构造出的新对象。

12var name = 'window';
function consoleName() {
	console.log(this.name);
}
let one = {
	name:'one',
	menthod: function () {
		console.log(this.name) // one,第二种调用
		consoleName(); // window,第一种调用
	}
}
one.menthod();

3let two = {
	name: 'two'
}
let three = {
	name:'three',
	menthod: function () {
		console.log(this.name);
	}
}
three.menthod(); // three
three.menthod.apply(two); // two, 第三种调用
three.menthod.apply(this)// window
three.menthod.apply(three); // three 

4function consoleName(name) {
	this.name = name;
}

const userName = new consoleName('four');
console.log(userName.name); // four, 第四种调用

说一下,consoleNmae函数在非严格模式下,是调用它的是window,所以会打印全局模式下的name,但如果是严格模式的话,输出则是undefined

二、 箭头函数补充

箭头函数比较特殊,不受上面四条规则的约束。箭头函数的 this 根据外层函数确定,而且箭头函数的 this 一旦被绑定,就无法改变。

猜你喜欢

转载自blog.csdn.net/kelly0721/article/details/102638684