JavaScript中this的工作原理
①.作为对象方法调用
var obj ={
x: 0,
y: 0,
move: function(){
this.x = x;
this.y = y;
}
}
point.move(1, 1);
//this被绑定到当前point对象上
this在函数执行时去获取对应的值,而不是在函数定义时。
ex:
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(x ,y){
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
②.函数调用
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){
this.x = x;
};
var moveY = function(y){
this.y = y;
}
moveX(x);
moveY(y);
}
};
point.moveTo(1, 1);
console.log(point.x);
//1
③.构造函数调用
this 会绑定到新创建的对象上,避免了绑定到全局对象上。
var x = 2;
function test(){
this.x = 1;
}
var a = new test();
console.log(x);
//2 全局的x
console.log(a.x);
//1 指向构造函数test中的x
④.使用apply或call调用this将会被设置为函数调用的第一个参数。
apply和call的区别在于一个要求传入的参数为数组,另一个要求分别传入。
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指向参数指定的对象上