Reputation: 1198
I have a following code:
<html>
<body>
<div>
<button id="but" >Click me</button>
</div>
<script>
var ele = document.getElementById("but");
ele.addEventListener('mousemove', myFunction);
this.model = {
'a': 'A',
'b': 'B'
}
function myFunction(e) {
alert(this.model.a);
}
</script>
</body>
</html>
When I hover the button it throws an error because I can't access model.a
. this
seems to refer to the DOME element. How can I access this.model
within that function?
Upvotes: 0
Views: 75
Reputation: 21
<html>
<body>
<div>
<button id="but" >Click me</button>
</div>
<script>
this.model = {
'a': 'A',
'b': 'B'
}
var ele = document.getElementById("but");
ele.addEventListener('mousemove', e => alert(this.model.a));
</script>
</body>
</html>
'this' works in a very strange way in JavaScript, it points us to the object which call the function. I think you can use arrow function to fix it, because they have more traditional behavior with 'this'.
Upvotes: 1
Reputation: 918
You can just use the window object. So you should change myFunction to:
function myFunction(e) {
alert(window.model.a);
}
Upvotes: 0