javascript中的this指向总结

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/littlebearGreat/article/details/81389305

javascript中,this的指向有下面4种情况:

1.  在构造函数中,this指向该构造函数new出来的那个对象。

function Foo() {
	this.a = 5;
	this.b = 10;
	this.c = this.a + this.b;
	console.log(this);		/*{a:5, b:10, c:15}*/
};

var c = new Foo();          /*{a:5, b:10, c:15}*/

2.  函数作为一个对象的一个属性,并且通过该对象调用此函数,此函数中的this指向该对象。

var a = 20;
var b = {
	a: 5,
	b: 10,
	c: function() {
		console.log(this.a);
	}
};
b.c();		/*5*/

var d = b.c;
d();		/*20*/

3.  调用函数call与apply,该函数中的this指向传入call或apply的那个对象。

4.  其它情况,函数中的this全指向window

猜你喜欢

转载自blog.csdn.net/littlebearGreat/article/details/81389305