代码1:
var obj = {
name:'xxx',
getThis:function(){
console.log(this)
}
}
obj.getThis()
代码2:
var obj = {
name:'xxx',
getThis:()=>{
console.log(this)
}
}
obj.getThis()
代码1输出obj本身,代码2输出window
代码3:
function Foo(name){
this.name = name
this.getThis = function(){
console.log(this)
}
}
var f = new Foo('xxx')
f.getThis()
代码4:
function Foo(name){
this.name = name
this.getThis = ()=>{
console.log(this)
}
}
var f = new Foo('xxx')
f.getThis()
我不理解,为什么代码3与代码4输出的this都是f。代码4不是应该输出window吗?
3中
f.getThis
,方法的调用者是f,所以this指向f4中arrow function不维护this,它的this是Foo构造函数里的this,所以指向实例