[ES6] 06. Arrow Function =>

ES6 arrow function is somehow like CoffeeScirpt.

CoffeeScript:

 //function                     call
coffee = ->                    coffee()
coffee=(message) ->            coffee("Yo"), coffee "Yo"
coffee=(message, other) ->     coffee("Yo", 2), coffee "Yo", 2

 

Now we rewrite a ES5 function to ES6 function:

ES5:

var greeting = function(message, name){
    return  message + name;
}

ES6:

First thing in ES6, we can remove the function keyword and add => on the right side of the params:

var greeting = (message, name) => {
   return message + name ;  
}

Second, we can remove 'return' and {};

var greeting = (message, name) => message + name

 

Example 1:

var f = () => 5; 
// 等同于
var f = function (){ return 5 };

Example 2:

 


//ES6
var msg = message => "Hello Es6"//ES5
var msg = function(message){
 return "Hello Es6";   
}

Example 3:

// 正常函数写法
[1,2,3].map(function (x) {
  return x * x;
});

// 箭头函数写法
[1,2,3].map(x => x * x);

Example 4:

// 正常函数写法
var result = values.sort(function(a, b) {
    return a - b;
});

// 箭头函数写法
var result = value.sort((a,b)=> a- b)

 

 

=> function helps to sovle the context problem:


 

复制代码
//ES5

var deliveryBoy = {
    name: "John",

    receive: function(){
        var that = this;
        this.handleMessage("Hello", function(message){
            //Here we have a very amazing handle function
            //which combine the name and message
            console.log(message + ' '+that.name);
        });
    },

    handleMessage: function(message, handler){
        handler(message);
    }

}

deliveryBoy.receive();
复制代码

In the code, we see:

console.log(message + ' '+that.name);

We use var that = this; and that.name to refer to "John". It looks quite confusing.

 

Arrow function helps us out of this:


 

复制代码
var deliveryBoy = {
    name: "John",

    receive: function(){this.handleMessage("Hello", message => console.log(message + ' '+this.name));
    },

    handleMessage: function(message, handler){
        handler(message);
    }

}

deliveryBoy.receive();
复制代码

Inside the code, we still use this.name to refer "John". This is because, => refer to the deliveryBoy object.

 

箭头函数有几个使用注意点。

  • 函数体内的this对象,绑定定义时所在的对象,而不是使用时所在的对象。
  • 不可以当作构造函数,也就是说,不可以使用new命令,否则会抛出一个错误。
  • 不可以使用arguments对象,该对象在函数体内不存在。

 

posted @   Zhentiw  阅读(532)  评论(0编辑  收藏  举报
(评论功能已被禁用)
编辑推荐:
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2013-11-20 5. How to set up a Activity
2013-11-20 4. Add override methods to class
2013-11-20 3. Layout -- 1
2013-11-20 2. Using 'dp' instead of 'px' to set text size
2013-11-20 1. Change the emulator screen size
点击右上角即可分享
微信分享提示