zoukankan      html  css  js  c++  java
  • ES6 箭头函数下的this指向和普通函数的this对比

    首先在网上摘抄借鉴了一段代码, 然后再这段代码里面进行分析,通过比较ES6的箭头函数和普通函数的this指指向, 分析其中的不同之处。下面就是代码片段var name = "window";

     1 var zhixiang= {
     2     name:"demo",
     3     // 传统函数
     4     normalFunction: function(){
     5         console.log(this.name);  // demo
     6         var _this= this;
     7         setTimeout(function(){
     8             console.log(this.name);  // window
     9             console.log(_this.name);  // demo
    10         },500)
    11     },
    12  
    13     // 箭头函数-作为异步回调  --- 只要是加了setTimeOut或者是setInterval的函数都会自动转为异步模式, 在执行的时候会先执行同步的代码,然后再执行这里面的代码
    14     arrowFunction:function(){
    15         setTimeout(()=>{
    16             console.log(this.name)  // demo   所以箭头函数在异步中还是有一定的作用域的问题
    17         },500)
    18     },
    19  
    20     // 箭头函数-作为直接执行的方法
    21     getName3:()=>{
    22         console.log(this.name)  // window   箭头函数就不存在作用域的情况,不需要像一般函数那样需要中转一下this的指向,不然就会报出找不到this的问题
    23     }
    24 };
  • 相关阅读:
    前端切图:自制简易音乐播放器
    SEO那些事:一句代码一键分享网站
    POJ 2553 Tarjan
    POJ 2186 Tarjan
    POJ 1236 Tarjan算法
    POJ 1330 Tarjan LCA、ST表(其实可以数组模拟)
    POJ 1470 Tarjan算法
    POJ 1985 求树的直径 两边搜OR DP
    POJ 3687 拓扑排序
    POJ 3522 Kruskal
  • 原文地址:https://www.cnblogs.com/lanveer/p/9355537.html
Copyright © 2011-2022 走看看