一直以来,this关键字都是我的知识盲区,虽然平时一直都有用到,但是都不是很理解this的指向,今天看了一篇文章,感觉受益匪浅,所以做个记录。参考文章地址https://www.jb51.net/article/74097.htm
1.首先确定它是不是用new进行调用的,如果是,那么this就指向new出来的对象
function a(x,y) {
this.x = x
this.y = y
}
var b = new a(1,2)
b.x // 1
b.y // 2
这里的this就指向new出来的b
2.如果不是new进行调用,那么看是否用了dot点调用。(用了dot调用)
var point = {
x : 0,
y : 0,
moveTo : function(x, y) {
this.x = this.x + x;
this.y = this.y + y;
}
};
point.moveTo(1,2)
这里用dot调用moveTo,那么moveTo里面的this就指向dot之前的对象。这里dot之前的对象就是point,所以this指向point
3.如果不是new进行调用,那么看是否用了dot点调用(没有用dot调用)
function func(x) {
this.x = x;
}
func(5); //this是全局对象window,x为全局变量
x;//x => 5
这里是函数直接调用,那么this就指向全局变量window,这里的this.x实际上等于window.x
var point = {
x : 0,
y : 0,
moveTo : function(x, y) {
var that = this // 加入这句,后面的this改成that,那么就可以把this引用指向point
// 内部函数
var moveX = function(x) {
this.x = x;//this 指向什么?window
};
// 内部函数
var moveY = function(y) {
this.y = y;//this 指向什么?window
};
moveX(x);
moveY(y);
}
};
point.moveTo(1,1);
point.x; //=>0
point.y; //=>0
x; //=>1
y; //=>1
之前一直不理解为什么这里的this是指向window,现在一目了然,因为它是函数直接调用,既不是dot调用,也不是new调用,所以这里的this指向window。如果要让this指向point,可以在moveTo函数里面加入var that = this。
4.apply() 和 call() 方法里面的this指向。
function Point(x, y){
this.x = x;
this.y = y;
this.moveTo = function(x, y){
this.x = x;
this.y = y;
}
}
var p1 = new Point(0, 0);
var p2 = {x: 0, y: 0};
p1.moveTo.apply(p2, [10, 10]);//apply实际上为p2.moveTo(10,10)
p2.x//10
实际上这还是dot调用,this之前dot之前的对象,这里就是p2。