js中,this的含义,箭头函数作用域问题

问题:"this"的含义

答:this指代当前作用域下的对象

问题:箭头函数的作用域是如何查找的

答:向外层作用域中,一层一层的查找,直到作用域中有this的定义。
而普通的function()函数中,this只指代当前作用域对象,如果没有对象定义,则指代全局对象,也就是window

普通的function()函数
const obj = {};
obj.info = "objInfo";

obj.bbb = function bbb() {
    console.log("obj.bbb()中的this→",this);
    // function(){this}
    };
obj.bbb();

此处的 “this” 打印 obj{}

为了更直观的理解,笔者做了实验,下面,开始套娃

须知:笔者懒得敲html,直接在node环境下测试的。有可能与浏览器结果有出入

function()函数 套 function()函数
const obj = {};
obj.info = "objInfo";

obj.bbb = function bbb() {
    function ccc() {
        console.log("obj.bbb(ccc())中的this→",this);
    };ccc();  
    // function(){function(this)}
    };
obj.bbb();

此处的 “this” 打印 window

function()函数 套 function()函数 套 function()函数
const obj = {};
obj.info = "objInfo";

obj.bbb = function bbb() {
    function ddd() {
        function eee() {
            console.log("obj.bbb(ddd(eee()))中的this→",this);
        };eee()
    };ddd();
    // function(){function(){funution(){this}}}
    };
obj.bbb();

此处的 “this” 打印 window

箭头函数

function()函数 套 箭头函数
const obj = {};
obj.info = "objInfo";

obj.bbb = function bbb() {
    let arrayA = () => {
        console.log("obj.bbb(arrayA())中的this→",this);
    };arrayA();    
    // function(){()=>{this}}
    };
obj.bbb();

此处的 “this” 打印 obj{}

function()函数 套 箭头函数 套 箭头函数
const obj = {};
obj.info = "objInfo";

obj.bbb = function bbb() {
    let arrayB = () => {
        let arrayC = () => {
            console.log("obj.bbb(arrayB(arrayC()))中的this→",this);
        };arrayC();
    };arrayB();
    // function(){()=>{()=>{this}}}
    };
obj.bbb();

此处的 “this” 打印 obj{}

重点!!!综合!!!!

function()函数 套 function()函数 套 箭头函数
const obj = {};
obj.info = "objInfo";

obj.bbb = function bbb() {
    function fff() {
        let arrayD = () => {
            console.log("obj.bbb(fff(arrayD()))中的this→",this);
        };arrayD();
    };fff();
    //  function(){function(){()=>{this}}}
    };
obj.bbb();

此处的 “this” 打印 window

function()函数 套 箭头函数 套 function()函数
const obj = {};
obj.info = "objInfo";

obj.bbb = function bbb() {
    function fff() {
        let arrayD = () => {
            console.log("obj.bbb(fff(arrayD()))中的this→",this);
        };arrayD();
    };fff();
    //  function(){function(){()=>{this}}}
    };
obj.bbb();

此处的 “this” 打印 window

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值