When I pass a function defined in an object as an event function in an event listener, the function doesn't work. For reference, here's the HTML code:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id='hi'>Hi</button>
<script src="script.js"></script>
</body>
</html>
And here's the JavaScript code (script.js):
var test = {
arr: [1,2,3],
hello: function() {
console.log(this.arr.length);
}
};
var a = document.getElementById('hi');
a.addEventListener('click', test.hello);
The function hello
from the object test
doesn't get executed when button is clicked, showing this error:
Uncaught TypeError: Cannot read property 'length' of undefined
at HTMLButtonElement.hello (script.js:6)
Are callback functions passed differently when they are properties of an object? Or this is due to some other issue relating to event listening?