首页 > 其他 > 详细

ES6学习笔记<二>

时间:2017-09-21 18:47:22      阅读:199      评论:0      收藏:0      [点我收藏+]

接着上一篇的说。

arrow functions 箭头函数

 => 更便捷的函数声明

    document.getElementById("click_1").onclick = function(){ console.log("say Hi!"); }
    document.getElementById("click_2").onclick = () => { let a = 1; let b = 2; console.log(a + b); }

之前的 function 声明可以被 => 代替,书写起来更便捷。

箭头函数还有个更炫酷也是最使用的用法。

先看个常见的例子:

    class people{
        constructor(){ this.age = 18; }
        say(){ setTimeout(function(){ console.log("I‘m " + this.age + " year old."); },2000) }
    }
    let children = new people();
    children.say();    // I‘m undefined year old.

这里的this指向内层function对象,所以出现undefined,这就是比较蛋疼的bug。为了方便理解上个截图说明

技术分享

传统解决方案:

    class people{
        constructor(){ this.age = 18; }
        say(){ 
            var self = this;
            setTimeout(function(){ console.log("I‘m " + self.age + " year old."); },2000) 
        }
    }
    let children = new people();
    children.say();    // I‘m 18 year old.

this在函数内传递给一个变量再使用。或者

    class people{
        constructor(){ this.age = 18; }
        say(){ 
            setTimeout(function(){ console.log("I‘m " + this.age + " year old."); }.bind(this),2000) 
        }
    }
    let children = new people();
    children.say();    // I‘m 18 year old.

bind(this) 指明this的对象

再来看看用 => 的做法

    class people{
        constructor(){ this.age = 18; }
        say(){ 
                setTimeout( ()=>{ console.log("I‘m " + this.age + " year old."); },2000) 
           }
    }
    let children = new people();
    children.say();    // I‘m 18 year old.

简单省事儿阅读清晰。

 

未完待续... ...

ES6学习笔记<二>

原文:http://www.cnblogs.com/MirageFox/p/7570032.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!