Reputation: 41
I try to find out, how it is possible to access an object through a string which has the same name as the object name. Is there any specific notations for the string to be interpreted as the object name?
Like in my example script:
<html>
<body>
<script>
var door = {"opened":false, "window":{"opened":false} };
function knocking(event){
var knockedThing = event.target.id;
alert(knockedThing);
alert("door is opened : " + knockedThing.opened);
alert("door window is opened : " + knockedThing.window.opened);
}
</script>
<button id="door" onclick="knocking(event)">A door</button>
</body>
</html>
The script can be run here: ---> https://www.w3schools.com/code/tryit.asp?filename=FX3JE6FP2UFQ
The goal of my script is to use the id "door" of the clicked button to access the object "door". But right now it doesn't work because the button id "door" is just a string name which have nothing to do with the object with same name.
How it is possible to make the connection without creating an object which would integrate the object "door" (to make this one accessible through the brackets notation)?
var house = {"door":{"opened":false, "window":{"opened":false} } };
Which would be accessible through bracket notation, like this:
alert(house[something]);
alert("door is opened : " + house[something].opened);
alert("door window is opened : " + house[something].window.opened);
Upvotes: 0
Views: 103
Reputation: 85767
<html>
<body>
<script>
var door = {"opened":false, "window":{"opened":false} };
function knocking(event){
var knockedThing = event.target.id;
alert(knockedThing);
alert("door is opened : " + window[knockedThing].opened);
alert("door window is opened : " + window[knockedThing].window.opened);
}
</script>
<button id="door" onclick="knocking(event)">A door</button>
</body>
</html>
Global variables are properties of the window
object, so you can access door
through window['door']
.
Upvotes: 1