pbarney
pbarney

Reputation: 2843

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?

Upvotes: 0

Views: 144

Answers (1)

Kevin Boucher
Kevin Boucher

Reputation: 16685

Use square bracket notation:

this.dataset[tempVariable];

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

Upvotes: 4

Related Questions