JavaScript中this的工作原理

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指向参数指定的对象上

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值