有人可以解释一下这个 JavaScript 吗?

huangapple go评论73阅读模式
英文:

Can someone explain this javascript?

问题

parentObj.obj.t() parentObj.obj.ta() https://mobdro.bio/

parentObj.obj.t() 是在父对象 parentObj 的上下文中执行的,因此它的 this 引用的是 parentObj.obj 对象。

parentObj.obj.ta() 使用了箭头函数,箭头函数的特性是它会捕获定义时所在的上下文,因此它的 this 引用的是全局作用域,而不是 parentObj.obj 对象。

希望这能帮助你理解为什么 parentObj.obj.ta()this 是全局作用域,而不是 parentObj

英文:
    const obj = {
        name: 'something',
        t: function() {
            console.log(this)
        },
        ta: () => {
            console.log(this)
        }
    }
    const parentObj = {
        name: 'cheeteh',
        obj [https://mobdro.bio/][1] 
    }

parentObj.obj.t() parentObj.obj.ta() https://mobdro.bio/ 

How is parentObj.obj.ta() the global scope and not the parentObj ?

can somebody help me?

[1]:

答案1

得分: 1

在JavaScript中,普通函数拥有它们自己的 this 上下文,它指的是调用该函数的对象。

当调用 parentObj.obj.t() 时,"t" 函数内部的 this 指向 parentObj.obj,也就是调用该函数的对象。

因此,"t" 方法会记录 parentObj.obj 对象。

另一方面,箭头函数不具备自己的 this 上下文。相反,它们继承了来自外部作用域的 this 值,而在这种情况下,是全局作用域(window)。

英文:

In JavaScript, regular functions have their own this context, which refers to the object that called the function.

When parentObj.obj.t() is invoked, this inside the "t" function refers to parentObj.obj, which is the object that called the function.

Therefore, the "t" method will log the parentObj.obj object.

On the other hand, arrow functions do not have their own this context. Instead, they inherit the this value from the surrounding scope, which in this case, is the global scope (window).

huangapple
  • 本文由 发表于 2023年6月26日 01:05:36
  • 转载请务必保留本文链接:https://go.coder-hub.com/76551563.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定