gpt4 book ai didi

javascript - 使用 'this' 获取 [object Object] 的名称

转载 作者:行者123 更新时间:2023-11-30 09:35:06 24 4
gpt4 key购买 nike

我正在使用一个我不知道全局对象名称(不,它不是窗口)的软件,但我想知道。

console.log(this)

给我[对象对象]

for(var property in this) {
console.log(property + "=" + this.property);
}

给我“this”的属性。

但是,我需要“this”的名称/id(我可以访问另一个上下文/对象中的属性的东西)。有没有可能得到它?

我已经searched为此,但找不到合适的解决方案。

最佳答案

您需要使用 bracket notationthis 上下文中获取属性值.

for(property in this) {
console.log(property + "=" + this[property]);
// ----^^^^^^^^^^^^^^----
}

您可以使用 Object.keys 获取对象属性返回属性名称数组的方法。


仅供引用:要在另一个上下文中访问 this 上下文,请使用在两个上下文中都有作用域的变量引用它(通常您可以使用全局变量)。

// initial variable or neglect to make it as global
var self;

/* cotext 1 start */

// define
self = this;

for(property in self) {
console.log(property + "=" + self[property]);
}
/* cotext 1 end */

/* cotext 2 start */

// use `self` to refer the context1
for(property in self) {
console.log(property + "=" + self[property]);
}

/* cotext 2 end */

关于javascript - 使用 'this' 获取 [object Object] 的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44025492/

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