Search code examples
javascriptvariablesindirect-objects

Javascript - variable for method name?


How can you reference a javascript object indirectly?

Suppose:

<div id="foo" data-munchy="bar" data-crunchy="baz">FooBar</div>

<script>
document.getElementById("foo").onclick = function() {
    tempVariable = 'munchy';
    console.log(this.dataset.tempVariable);
}
</script>

How can I access this.dataset.{someVariable}? In this case, this.dataset.tempVariable

Is it only possible using eval or window?


Solution

  • Use square bracket notation:

    this.dataset[tempVariable];
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors