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