我无法从另一个已在构造函数中实例化的函数访问JavaScript变量。它返回undefined
。
我正在实例化类Box
的新对象,并在构造函数中,定义实例变量,创建HTML元素和设置事件侦听器。此侦听器的处理程序clickHandler
是在原型上定义的函数。从clickHandler
开始,我正在尝试访问this.selected
变量。但我得到undefined
。
代码:
HTML
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<div id="element1"></div>
<br/>
<div id="element2"></div>
<script type="text/javascript" src="script.js"></script>
<script>
init([{id: "element1"}, {id: "element2"}]); //call init function
</script>
</body>
</html>
Javascript script.js
function Box(id, count) { //the class
this.selected = false; //need this variable in clickHandler
this.div = document.createElement("div");
this.div.id = "container" + count;
this.div.style.width = "250px";
this.div.style.height = "150px";
this.div.style.border = "1px solid black";
document.getElementById(id).appendChild(this.div);
this.div.addEventListener("click", this.clickHandler, false); //add event listener on the created div element
}
Box.prototype.clickHandler = function() { //click handler
console.log("clickHandler, selected = " + this.selected); // undefined
};
function init(settings) {
//var obj;
for(var i = 0; i < settings.length; i++) {
new Box(settings[i].id, (i+1)); //instantiate new object
}
}
如何在各种事件处理函数中访问this.selected
变量?我计划监听多个事件,并需要this.selected
变量。谢谢你的帮助。
答案 0 :(得分:0)
将处理程序添加到:
this.div.addEventListener("click", this.clickHandler.bind(this), false);
这会将对象绑定为回调函数中的“this”上下文。
function Box(id, count) { //the class
this.selected = false; //need this variable in clickHandler
this.div = document.createElement("div");
this.div.id = "container" + count;
this.div.style.width = "250px";
this.div.style.height = "150px";
this.div.style.border = "1px solid black";
document.getElementById(id).appendChild(this.div);
this.div.addEventListener("click", this.clickHandler.bind(this), false);
}
Box.prototype.clickHandler = function() { //click handler
console.log("clickHandler, selected = " + this.selected); // undefined
};
function init(settings) {
//var obj;
for(var i = 0; i < settings.length; i++) {
new Box(settings[i].id, (i+1)); //instantiate new object
}
}
init([{id: "element1"}, {id: "element2"}]); //call init function
<div id="element1"></div>
<br/>
<div id="element2"></div>