普通函数里的this指向:
function test(){
console.log(this)
}
test()//window
test()等价于window.test()
对象形式
var name="outername"
var o={
name:"innername",
getname:function(){
console.log(this.name)
}
}
o.getname()//innername
因为是o调用的o下面的getname方法,所以this指向o
对象形式中的箭头函数
var name="outername"
var o={
name:"innername",
getname:()=>{
console.log(this.name)
}
}
o.getname()//outername
箭头函数的this对象:就是定义时所在的对象,而不是使用时所在的对象,也就是根据外层(函数或者全局)作用域来决定this
例子继续
var name="outername"
var o={
name:"innername",
getname:function(){
setTimeout(()=>console.log(this.name),1000)
}
}
o.getname()//innername
这个例子里的箭头函数this往外层找作用域,找到了,这个箭头函数处于getname函数的作用域,getname是o对象下面的,箭头函数里的this也就指向o对象
function foo() {
setTimeout(() => {
console.log('id:', this.id);
}, 100);
}
var id = 21;
foo.call({ id: 42 });// id: 42
这个foo函数本来是window.foo(),this是window,call改变了this 的执行上下文,foo里的this就指向call()传进去的对象
如果直接执行foo() 就会打印出id :21
总结:
普通函数this指向:谁调用了函数 函数里的this就指向谁
箭头函数的this指向:就是定义时所在的对象,而不是使用时所在的对象,也就是根据外层(函数或者全局)作用域来决定this
「三年博客,如果觉得我的文章对您有用,请帮助本站成长」
共有 0 条评论 - ES6箭头函数的this指向