gpt4 book ai didi

Title: JavaScript this behavior inside an arrow function used in Object.defineProperty [duplicate](标题:在对象中使用的箭头函数内的此行为。定义属性[复制])

转载 作者:bug小助手 更新时间:2023-10-25 13:40:47 31 4
gpt4 key购买 nike




Question:

问题:


I'm encountering unexpected behavior when using an arrow function as a getter in Object.defineProperty in JavaScript. Here's my code:

在Java中使用箭头函数作为对象的getter时,我遇到了意外的行为。以下是我的代码:


"use strict";

const obj = {
a: 10,
};

Object.defineProperty(obj, "b", {
get: () => {
console.log(this.a, typeof this.a, this);
return this.a + 10;
},
});

When I try to access obj.b, the output is unexpected:

当我尝试访问obj.b时,输出是意外的:


this.a is undefined
typeof this.a is 'undefined'
this refers to the global object (Window in a browser environment)
I expected this to refer to the obj object. Can someone explain why this behavior occurs and how to achieve the desired behavior?

A是未定义的类型。a是未定义的。这是指全局对象(浏览器环境中的窗口)。我原以为这是指obj对象。谁能解释一下为什么会发生这种行为,以及如何达到预期的行为?


更多回答

See the MDN page about this and note examples of getters/setters as functions: Object.defineProperty(o, "b", { get() { return bValue; }, ... developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

有关这一点,请参阅MDN页面,并注意作为函数的getters/setters的示例:Object.fineProperty(o,“b”,{get(){Return bValue;},...Developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…

优秀答案推荐


In arrow functions, this retains the value of the enclosing lexical context's this. In other words, when evaluating an arrow function's body, the language does not create a new this binding. Source



Since your arrow function is defined in the global scope, it's bound to window.

因为您的箭头函数是在全局作用域中定义的,所以它绑定到Window。


If you use a regular function, it's going to be bound to the object.

如果使用正则函数,它将绑定到对象。


更多回答

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com