当我在事件侦听器中将对象中定义的函数作为事件函数传递时,该函数不起作用。供参考,这是HTML代码:
<!DOCTYPE html>
<html>
<head></head>
<body>
<button id='hi'>Hi</button>
<script src="script.js"></script>
</body>
</html>
这是JavaScript代码(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);
单击按钮时,对象hello
中的函数test
未执行,显示此错误:
Uncaught TypeError: Cannot read property 'length' of undefined
at HTMLButtonElement.hello (script.js:6)
当回调函数是对象的属性时,传递的回调函数是否有所不同?还是这是由于其他与事件监听有关的问题?