JS ES6 箭头函式 DAY73

箭头函式

传统函式

const callName = function(someone){    return '我是' +  someone;}console.log(callName('皮杰先生'));

箭头函式

// 箭头函式// 若是程式码内容为表达式时,不需要大括号{}// 若只有一个参数 可省略括号const callName = someone => '我是' + someone;console.log(callName('皮杰先生'));

与传统函式不同之处

没有arguments参数

传统函式

var nums = function(){    console.log(arguments);}nums(1,2,3,4,50,100);

箭头函式

// arguments is no definedvar nums = () =>{    console.log(arguments);}nums(1,2,3,4,50,100);

解决方式

其余参数
原型是阵列(与 arguments 不同)

var nums = (...arg) =>{    console.log(arg);}nums(1,2,3,4,50,100);
this 绑定的差异

箭头函式没有自己的 this

传统函式

var myName = '全域';var person = {    myName:'皮杰先生',    callName: function(){        console.log('1',this.myName); // 1 皮杰先生        setTimeout(function(){            console.log('2',this.myName); // 2 全域            console.log('3',this); // window        })    }}person.callName();

箭头函式

var myName = '全域';var person = {    myName:'皮杰先生',    callName: function(){        console.log('1',this.myName); // 1 皮杰先生        setTimeout(()=>{             // 这里会用外层作用域的 this            console.log('2',this.myName); // 2 皮杰先生            console.log('3',this); // person        })    }}person.callName();
var myName = '全域';var person = {    myName:'皮杰先生',    callName: ()=>{        console.log('1',this.myName); // 1 全域        setTimeout(()=>{             // 这里会用外层作用域的 this            console.log('2',this.myName); // 2 全域            console.log('3',this); // window        })    }}person.callName();

也无法透过 call,apply,bind 重新给予 this

const family = {    myName:'123',}const fn = (a,b) =>{    console.log(this,a,b); // window 小黑 小白}fn.call(family,'小黑','小白');
箭头函式无法作为建构函式使用
const fn = function(a){    this.name = a;}const ArrowFn = a =>{    this.name = a;}console.log(fn.prototype);console.log(ArrowFn.prototype); // undefinedconst a = new fn('a');console.log(a);const b = new ArrowFn('b');console.log(b);

那今天的介绍就到这里
若有任何问题 或 内容有误
都可以跟我说唷http://img2.58codes.com/2024/emoticon41.gif


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章