zoukankan      html  css  js  c++  java
  • 关于es6的箭头函数使用与内部this指向

    特型介绍:箭头函数是ES6新增的特性之一,它为JS这门语言提供了一种全新的书写函数的语法。

    'use strcit';
    let arr = [1,2,3];
    //ES5
    let es5 = arr.map(function(n){
        return n*2;
    });
    //ES6
    let es6 = arr.map(n => n*2);
    console.log(es5);    //[2,4,6]
    console.log(es6);    //[2,4,6]

    箭头函数简化了原先的函数语法,不需要再写 function ,如果函数体只有一行代码的话连 return 都不用写,这个特性对于热衷于简化流程和工作的程序员来说相当对胃口。

    箭头函数支持两种模式的函数体写法,我们姑且叫他简洁函数体和块级函数体。

    'use strcit';
    // 简洁函数体
    let fn = x => x * x;
    
    // 块级函数体
    let fn = (x, y) => {return x + y;};

    简介函数体默认会把表达式的结果返回,块级函数体需要手动 return 。如果想要返回一个对象又想使用简洁函数体的话,需要这么写:

    'use strcit';
    let fn = () => ({});
    fn();   // {}

     如果写成 var fn = () => {} ,那么执行 fn() 只能返回 undefined 。

    'use strict';
    //第一种
    let Person = function(){
        this.age = 2;
        let that = this;
        setTimeout(function(){
         that.age++;
            console.log(that.age);
        },1000);
    };
    
    //第二种
    let Person = function(){
        this.age = 2;
        setTimeout(function(){
         this.age++;
            console.log(this.age);
        }.bind(this),1000);
    };
    new Person();

    之前我们想操作setTimeout参数function内部的this可能会用上述两种方法,看上去不错了, 但是现在有了箭头函数就不一样了,代码如下:

    'use strict';
    let Person = function(){
        this.age = 2;
        setTimeout(() => {
         this.age++;
            console.log(this.age);
        },1000);
    };
    new Person();  

    由于箭头函数已经绑定了this 的值,即使使用apply或者call也不能只能起到传参数的作用,并不能强行改变箭头函数里的this。

    'use strict';
    let obj = {
        x:1,
        show1:function(y){
            let fn = y => y+this.x;
            return fn(y);
        },
        show2:function(y){
            let fn = v => v + this.x;
            let whatever = {
                x: 2
            };
            return fn.call(whatever, y);
        }
    };
    console.log(obj.show1(1));    //2
    console.log(obj.show2(2));    //3

    箭头函数不能与new 关键字一起使用,会报错

    'use strict';
    let Fn = () => {
        this.a = 1;
    };
    let f = new Fn();    // Error
  • 相关阅读:
    spring-boot快速搭建解析
    springmvc处理ajax跨域
    Spring-AOP解析
    springmvc注解
    springmvc源码分析
    Spring源码分析
    JAVA性能优化
    数据取舍
    命令行控制
    Junit常用操作
  • 原文地址:https://www.cnblogs.com/tween/p/5440941.html
Copyright © 2011-2022 走看看