this 与 作用域 面试题

70 阅读1分钟

this面试题

window.onload = function(){
    var length = 10;
    function test() {
        console.log( this.length )
    )
    var obj = {
        length: 100,
        action: functioh(test){
            test()
            arguments[0]();
        }
    }
obj.action(test,1,[2,3],4) 
分析:
1. window.onload 是立刻执行的
2. 执行完成存在GO,AO

执行过程
obj.action(test,1,[2,3],4) 触发,进行obj.action中
test函数单独调用,所以 this 指向 window,所以 window.length = 10
arguments[0]()  执行时,根据 this 指向会指向调用者的方法无论是 obj.xxxx 或是 obj[xxxx] 或是 obj['xxxx']
都是属于调用者,此 this 都会指向调用者,所以这里 this 还指向 arguments,这里的 this.length 其实是求
arguments.length, 所以 arguments.length = 4 

作用域面试题

预解析(变态解析):预解析会把var,function关键先一步声明

预解析对于全局的GO(global object)执行如下

console.log(a)  // undefined
var a = 1

先进行变量提升
进行函数声明提升
执行程序

预解析对于全局的AO(actived object)执行如下

function a (a){
    console.log(a) // undefined
    var a = 1
    console.log(a) // 1
}

先进行变量提升
进行实参赋值
进行函数声明提升
执行程序

当全局和局部都有同名的变量时间,全局变量不作用于局部变量

console.log( a )  //不会报错  结果是 undefined
var a = 10 

var a=10;
function test(){
    console.log(a);
    a=108;
    console.log(this.a);
    var a;
    console.log(a);
}
test()
预解析:

全局预解析
GO:{
    var a ---> undefined
    function -> undefined
}
局部预解析
AO:{
    var a ---> undefined
}

**预解析结束**

分析过程:
GO:{
    a ---> 10
}
执行test()
AO:{
    a ---> undefined  ---> 108
}

所以刚执行 test() 的时候, 第一个 console.log(a) 是 undefined ,第二个是 window.a10 ,第三个是已经赋值的
a108