几道题目看懂js中的this

首先

1、箭头函数本身没有this

2、非严格环境下this指向外层首个非箭头函数的函数的this  严格环境undefiend

3、箭头函数内部为静态作用域(就是指作用域是根据程序在编译的时候就确定this 不受调用的对象影响)

直接上code

var obj = {
    a:function() {
        return function(){
            return ()=>{
                console.log(this)
            }
        }
    }
}
obj.a()()() //window

首先调用  obj.a()  返回一个匿名函数 暂取个代称 F

下一步 F() 可以看做由全局范围所调用 故该匿名函数 this 指向 window   执行后返回了箭头函数 暂取个代称 f

最后 f() 由箭头函数第二点规则 匿名函数 F 为箭头函数 f 的外层首个非箭头函数的函数  故 匿名函数F 的 this 就是箭头函数的 this

var obj = {
    a:function() {
        return ()=>{
            return ()=>{
                console.log(this)
            }
        }
    }
}
obj.a()()() //obj

现在把第二个匿名函数也改成箭头函数 则最内层的 this 指向就变为最外层的函数 a 也就是 this 指向 obj

var obj = {
    a:function() {
        return ()=>{
            return function(){
                console.log(this)
            }
        }
    }
}
obj.a()()() //window

但当继续将最内层的箭头函数改成匿名函数时 输出的结果和第一个例子的情况一样为 window

根据之前说的箭头函数规则 可以知道第二层的箭头函数 this 指向 obj 但由于最内层为匿名函数 除特殊情况外匿名函数都指向全局对象 故输出 window

如果需要外层 this 则可以使用闭包保留 this 如:var _this = this  内层调用 _this

如果将 a 函数改为箭头函数后 根据之前的内容可以得出 不管内层函数使用什么写法都输出 window

function foo(){
    this.a= '123'  
    return []
}

var Foo = new foo
console.log(Foo.a) //undefined

function foo(){
    this.a= '123'  
    return /test/g
}

var Foo = new foo
console.log(Foo.a) //undefined

function foo(){
    this.a= '123'  
    return '/test/g'
}
var Foo = new foo
console.log(Foo.a) //123

function foo(){
    this.a= '123'  
    return Symbol(321)
}
var Foo = new foo
console.log(Foo.a) //123

可以看出当函数返回值为值类型时 this 指向正常 但当返回值为引用类型时 this 指向返回的对象

 

posted @ 2019-01-16 14:34  莫非王臣  阅读(372)  评论(0编辑  收藏  举报