您的位置:首页 > 其它

普通函数与es6箭头函数-this指向--当call遇到箭头函数超全例子

2019-05-18 12:52 330 查看

普通函数与es6箭头函数-this指向问题-超全的例子详解

this问题

带着结论看例子更容易理解
1丶普通函数this指向调用当前函数的对象,箭头函数是所在上级普通函数(若父级不是普通函数,一直往上找,到window为止)的调用者。
2丶箭头函数.call()不会改变this的指向,但是也能成功调用箭头函数

例子1

var id=0;
let json={
id:1,
fun1 :function(){
console.log(this.id)//调用时候的对象
},
fun2:()=>{
console.log(this.id)//定义普通函数所在的对象
}
}
json.fun1()//1;
let x=json.fun1;
x();//0
json.fun2()//0;
let y=json.fun2;
y();//0

例子2

var bol=true;
let json={
bol:false,
fun1 :function(){//普通函数
!function(){//普通函数自调用
console.log(this.bol);
}();
},
fun2:()=>{//箭头函数
+function(){//普通函数自调用
console.log(this.bol);
}();

},
fun3(){//普通函数
(()=>{console.log(this.bol)})()//箭头函数自调用
},
fun4:()=>{//箭头函数
(()=>{console.log(this.bol)})()//箭头函数自调用
}
}
json.fun1();//true
json.fun2();//true
json.fun3();//false
let x=json.fun3;
x();//true;
json.fun4();//true

例子3

var bol=true;
let json={
bol:false,
fun(){//普通函数
(()=>{//箭头函数自调用
(()=>{console.log(this.bol)})()//箭头函数自调用
})()
},
fun2:()=>{//箭头函数
+function(){//普通函数自调用
(()=>{console.log(this.bol)})();
}();
},
fun3:()=>{//箭头函数
+function(){//普通函数自调用
(()=>{console.log(this.bol)})();
}.call(json);//让this指向json
},
fun3 ()  { //普通函数
~function () { //普通函数自调用
(() => { console.log(this.bol)})();
}.call(this);//让this指向调用者,当调用者改变的时候this也改变了
},
fun4 ()  { //普通函数
~function () { //普通函数自调用
(() => {console.log(this.bol) })();
}.call(json);//让this指向json,调用者改变this始终指向json
}
}
json.fun()//false;
let x=json.fun;
x()//true;
json.fun2();//true
json.fun3();//false
let y=json.fun3;
y();//true
json.fun4();//false
let z=json.fun4;
z();//false

例子4

let json={
demo:()=>{
(()=>{console.log(this)}).call(json);
},
demo2:()=>{
+function(){
console.log(this)
}.call(json)
}
}
json.demo()//window
json.demo2()//json
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: