1.作为对象方法调用
2.函数调用
var point={
x:0,
y:0,
move:function(x,y){
this.x=x;
this.y=y;
}
}
point.move(1,1);//this被绑定到当前对象,即point 对象
this在函数执行时去获取对应的值,而不是在函数定义时。
eg:
var a = {
aa: 0,
bb: 0,
fun: function(x, y) {
this.aa = this.aa + x;
this.bb = this.bb + y;
}
};
var aa = 1;
var b = {
aa: 0,
bb: 0,
fun: function() {
return this.aa;
}
};
a.fun(3, 2);
console.log(a.aa); //3 this指向对象本身
console.log(b.fun()); //0 this指向对象本身
(function(aa) {
var c = aa();
console.log(c);
})(b.fun); //1 //由于fun在该处执行,导致this不再指向对象本身,而是window
2.函数调用
var x = 1;
function test() {
this.x = 0;
}
test();
console.log(x);//0 函数调用 this被绑定到全局对象上。
缺点:内部函数的this也绑定全局对象,而我们希望这里的this绑定到其外层函数对应的对象上
解决方法:将this保存在一个变量中,再运用该变量即可
;
var point = {
x: 0,
y: 0,
moveTo: function(x, y) {
var that = this;
console.log(that);
var moveX = function(x) {
that.x = x;
};
var moveY = function(y) {
that.y = y;
}
moveX(x);
moveY(y);
}
};
point.moveTo(1, 1);
console.log(point.x);//1
3.构造函数调用。
this会绑定到新创建的对象上,避免了this绑定到全局对象上。
var x = 2;
function test() {
this.x = 1;
};
var a = new test();
console.log(x);//2
console.log(a.x);//1
4.使用apply或call调用this将会被现实设置为函数调用的第一个参数
apply与call的区别在于一个要求传入的参数为数组,一个要求分别传入。
以apply为例
var name = "window";
var aa = {
name: "Bob",
showName: function() {
return this.name;
}
};
var other = {
name: 'Jack'
}
console.log(aa.showName()); //'Bob' this对象绑定到当前对象
console.log(aa.showName.apply()); //'window' apply()无参数时,this对象绑定到全局对象
console.log(aa.showName.apply(other)); //'Jack' 有参数时,this指向参数指定的对象
}