zoukankan      html  css  js  c++  java
  • ES6 箭头函数使用(this作用域总结)

    前言

    ES6中添加了箭头函数,可以更方便绑定this作用域了 O.o
    至于使用,我觉得一个实例就够了 我不信看完还有不会用的

    实例代码

    const x = 1;
    this.x = 4; // this  default {}
    global.x = 2;
    
    let fun1 = () => {
        console.log('fun1', this.x); // 4 this => this
    };
    
    
    const obj = {
        x: 3,
        fun: function () {
            console.log('fun', this.x); // 3 this => obj
            let fun2 = () => {
                console.log('fun2', this.x); // 3 this => fun => obj
            };
            let fun3 = function () {
                console.log('fun3', this.x); // 2 this => global
            };
            let fun4 = fun1;
            let fun6 = fun3.bind(this);
            fun1();
            fun2();
            fun3();
            fun4(); // 4 this => this
            fun6(); // 3 this => obj
        }
    };
    obj.fun();
    console.log(this); // { x: 4 }
    console.log(this.x); // 4 this => this
    
  • 相关阅读:
    5.9上午
    5.4下午
    5.4上午
    5.2上午
    4.19下午
    4.18上午
    4.17下午
    4.17上午
    4.12下午
    4.13下午
  • 原文地址:https://www.cnblogs.com/xpengp/p/13048411.html
Copyright © 2011-2022 走看看