有没有办法“得到”?就像getElementById()能够获取html元素对象一样,使用函数来获取javascript

Is there a way to "get" javascript objects using a function in the same way getElementById() is able to get html element objects?

本文关键字:获取 对象 一样 javascript 函数 元素 得到 有没有 getElementById 就像 html      更新时间:2023-09-26
document.getElementById('coolid').innerHTML = "pretty cool";

上面的代码将,据我所知,访问一个名为"coodid"的html元素对象,该对象作为一个元素对象,有一个属性"innerHTML",允许我用文本"pretty cool"替换html节点文本。

我也知道getElementsByName()和getElementsByClass()等…这些都允许我访问DOM元素(据我所知是对象)。好的,那太好了。但是否也有办法访问我创建的对象呢?这样的:

var person = {姓名:"约翰",}

object.reallyCoolImaginaryGetMyObjectFunction('person').name = "Tom";

我知道这可能看起来很奇怪,甚至可能毫无意义,但只是出于好奇,我一直在想这个。有人知道吗?谢谢。

如果它们存储在对象中,则可以,但有一种特殊情况(全局变量)会自动存储在window中。

可以使用括号表示法和字符串,例如:

var obj = {
    foo: "bar"
};
console.log(obj["foo"]); // "bar"

当然,如果它是一个全局变量:

console.log(window["foo"]); // "bar"

…因为全局变量是全局对象的属性,我们可以在浏览器中将全局对象称为window

详细信息:JavaScript有两种方式来访问属性:点表示法与文字名称(obj.foo)和括号表示法与字符串(obj["foo"])。在后一种情况下,字符串可以是任何表达式的结果,例如:

// These all do the same thing, in the end
console.log(obj["foo"]);
console.log(obj["f" + "o" + "o"]);
var x = "foo";
console.log(obj[x]); // x contains the string