zoukankan      html  css  js  c++  java
  • JS的箭头函数this作用域

    name="小刚";
    let student={
        name:"小明",
        printLog:function(){
            // 这里绑定了顶层作用域,可以使用变量与方法
            console.log(this)
        },
        printArrowLog:()=>{
            // 这里不知道绑定的是哪个作用域,有知道的大咖请回答下
            console.log(this)
        }
    }
    
    student.printLog();
    /*
        { name: '小明',
          printLog: [Function: printLog],
          printArrowLog: [Function: printArrowLog] 
        }
    */
    student.printArrowLog();
    /*
        {}
        这里返回了空对象,说明this不是指向window全局对象,也不是指向student对象。奇葩
    */
    name="小刚";
    let student={
        name:"小明",
        printLog:function(){
            // 这里绑定了顶层作用域,可以使用变量与方法
            return ()=>{
                console.log("printLog Arrow:"+this)
            }
        },
        printLog1:function(){
            // 这里绑定了全局作用域,可以使用window对象的属性
            return function(){
                console.log("printLog1:"+this)
            }
        },
        printLog2:function(){
            // 这里绑定了全局作用域,可以使用window对象的属性
            (function(){
                console.log("printLog2:"+this)
            })()
        }
    }
    
    sayhello=student.printLog();
    sayhello1=student.printLog1();
    
    sayhello();
    /*
        printLog Arrow:小明
        this指向:printLog Arrow:[object Object]
        从这里我们可以看出这里使用的是student对象里的顶层属性,没有说明问题
    */
    
    sayhello1();
    /*
        printLog1:小刚
        this指向:printLog1:[object global]
        从打印的结果来看,我们可以看到打印的name值为小刚,是我在全局进行生命的name属性,说明在外部进行调用,this指向window全局对象
    
    */
    
    student.printLog2();
    /*
        printLog2:小刚
        this指向:printLog1:[object global]
        从打印的结果来看,我们可以看到打印的name值为小刚,是我在全局进行生命的name属性,说明生命调用写在一起,this指向window全局对象
    */
    name="小刚";
    let student={
        name:"小明",
        functions:{
            name:"小飞",
            printLog:function(){
                // 这里绑定了functions对象作用域,可以使用内部的变量与方法
                return ()=>{
                    console.log("printLog:"+this.name)
                }
            },
            printLog1:function(){
                // 这里绑定了顶层作用域,可以使用window的变量与方法
                return function(){
                    console.log("printLog1:"+this.name)
                }
            }
        }
    }
    
    
    var pl=student.functions.printLog();
    pl();
    /*
        printLog:小飞
    
    */
    
    
    var pl1=student.functions.printLog1();
    pl1();
    /*
        printLog1:小刚
    */
    
    /*总结:根据name的值不同,可以查到使用的是哪个作用域的值,进而可以知道this的指向*/

    function方法调用call和apply的使用方式:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/call

    复制请注明出处,在世界中挣扎的灰太狼
  • 相关阅读:
    21322
    9-1
    作业五1
    作业五2
    实验9-2
    作业4函数应用
    实验九 1
    实验八 数组2 输出一张九九乘法口诀表。要求必须将乘积放入一个二维数组中,再输出该数组,程序运行效果如下
    实验八 (调试)
    实验6剩余部分
  • 原文地址:https://www.cnblogs.com/XingXiaoMeng/p/11437674.html
Copyright © 2011-2022 走看看