zoukankan      html  css  js  c++  java
  • function 与 => 的区别

    在JS中,箭头函数并不是简单的function(){}匿名函数的简写语法糖,实际上,箭头函数和匿名函数有个明显的区别:箭头函数内部的this是词法作用域,在编写函数时就已经确定了。而匿名函数的this指向运行时实际调用该方法的对象,无法在编写函数时确定。

    我们看一下下面的例子:

     1 function Test() {
     2     this.num = 100;
     3 
     4     this.func = function(){
     5         console.log(this.num); // 100
     6         setTimeout(function(){
     7             console.log(this.num); // undefined
     8         }, 500);
     9     };
    10 }
    11 
    12 var obj = new Test();
    13 obj.func();

    这里的方法里调用了setTimeout函数,该函数500毫秒后调用我们定义的函数时,实际上是window对象调用的,所以这时匿名函数的this是指向window而不是指向obj了。

    在箭头函数出现之前一般都是这么写的:

     1 function Test() {
     2     this.num = 100;
     3 
     4     this.func = function(){
     5         console.log(this.num); // 100
     6         var that = this;
     7         setTimeout(function(){
     8             console.log(that.num); // 100
     9         }, 500);
    10     };
    11 }
    12 
    13 var obj = new Test();
    14 obj.func();

    这是利用了闭包的概念。箭头函数可以看做这种方式的语法糖。

    如下:

     1 function Test() {
     2     this.num = 100;
     3 
     4     this.func = function(){
     5         console.log(this.num); // 100
     6         setTimeout(() => {
     7             console.log(this.num); // 100
     8         }, 500);
     9     };
    10 }
    11 
    12 var obj = new Test();
    13 obj.func();

    箭头函数和普通函数的区别

    • 不可以当做构造函数,也就是说,不可以使用 new 命令,否则会抛出错误。
    • this、arguments、caller等对象在函数体内都不存在。
    • 不可以使用 yield 命令,因此箭头函数不能用作 Generator 函数。

    总结

    箭头函数除了传入的参数之外,其它的对象都没有!在箭头函数引用了this、arguments或者参数之外的变量,那它们一定不是箭头函数本身包含的,而是从父级作用域继承的。

  • 相关阅读:
    Codeforces 1255B Fridge Lockers
    Codeforces 1255A Changing Volume
    Codeforces 1255A Changing Volume
    leetcode 112. 路径总和
    leetcode 129. 求根到叶子节点数字之和
    leetcode 404. 左叶子之和
    leetcode 104. 二叉树的最大深度
    leetcode 235. 二叉搜索树的最近公共祖先
    450. Delete Node in a BST
    树的c++实现--建立一棵树
  • 原文地址:https://www.cnblogs.com/hammerc/p/7390424.html
Copyright © 2011-2022 走看看