普通函数与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
相关文章推荐
- 关于严格模式普通函数和箭头函数中this的指向问题
- javascript this 和 es6 箭头函数this 的理解以及call()、apply()、bind()的用法
- es6箭头函数this指向
- ES6---箭头函数与function定义函数有什么区别?在箭头函数中,this指向,构造函数,变量提升是如何表现的?
- ES6 箭头函数this指向问题
- ES6中箭头函数this指向的问题
- ES6箭头函数内this指向问题
- 十,(补充)ES6中箭头函数this的指向
- ES6的箭头函数this和普通函数的this区别
- ES6箭头函数this指向问题
- es6 箭头函数的this 指向问题
- ES6语法---箭头函数/关于this指向
- ES6中箭头函数的this指向
- ES6 箭头函数 this 指向
- 箭头函数、普通函数的区别以及this指向问题。
- es6-箭头函数中的this使用
- JS箭头语法以及箭头函数this指向问题
- ES6箭头函数中的this绑定问题
- 关于ES6箭头函数中的this问题
- 原生 ES6极简删删除节点 箭头函数,正则,call