Answer the question
In order to leave comments, you need to log in
How to reach the property of a Javascript object from its own function when running it through an EventListener or why this === e.target?
I was looking for an answer, but it's hard to formulate a request. In general, a hackneyed problem with this in js:
<html>
<head>
<title>Deep Thought</title>
<script type="text/javascript">
var deepThought = {
answer: 42,
alertAnswer: function (e) {
//need 42!!
}
}
onload = function() {
document.getElementById("button").addEventListener('click', deepThought.alertAnswer);
}
</script>
</head>
<body>
<button id="button">
alert the Answer to the Ultimate Question of Life,
The Universe, and Everything
</button>
</body>
</html>
Answer the question
In order to leave comments, you need to log in
you need to run the function through an event, and in this case this === e.target
document.addEventListener('click', function (e) {
console.log(e.target); // Где кликнули
console.log(this); // Всегда document
}, false);
document.addEventListener('click', deepThought.alertAnswer.bind(deepThought), false);
For example, create an object using new function, store a reference to the object itself in a variable, and access the object from the method not through this, but through this variable:
var deepThought = new function() {
var self = this;
this.answer = 42;
this.alertAnswer = function() {
alert(self.answer);
};
}
Sorry for the flood, but I found the solution myself :)
And if the EventListener needs to be added inside another function of the deepThought object, then it should look like this:
var deepThought = {
...
onLoad: function () {
var a = this;
document.getElementById("button").addEventListener('click', function (e) {a.alertAnswer();});
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question