this指向问题

this指向问题

// 例1
 var length = 100
 function test() {
   console.log(this.length);
 }
 var obj = {
   length: 4,
   action: function(test) {
     test() 
     arguments[0]() 
   }
 }
 obj.action(test, [1, 2, 3])

this指向规则:运行一个函数,有没有调用者,如果有指向调用者,没有默认为全局即window

// 测试
function test1() {
 console.log(this) // 输出arr数组
}
var arr = [test1, 1, 2]
arr[0]() // obj['id']() <=> obj.id()

// arguments 所有参数集合 类似于数组
function test2() {
 console.log(arguments.length) // 输出 4
 }
 test2(1,2,3,4)

所以最后输出:
100
2

// 例2
  var a = 10
  function test2() {
     console.log(a);
     a = 100
     console.log(this.a);
     var a;
     console.log(a);
   }
   test2()

1.js存在预解析

//js解析过程
// 预解析
var a;
function test2(){}
依次执行
a=10;
test2();
// 执行test2时,预解析
var a;
// 依次执行
console.log(a);
a = 100;
console.log(this.a);
console.log(a);

2.局部变量和全局变量同名时,全局变量是不会作用与局部变量的作用域的
所以最后输出:
undefined
10
100

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值