I have the following object:
var object = {
attr1 : "hello",
myFunc : function() {
alert(this.attr1); //This should alert "hello"
},
initialize : function() {
document.getElementById("myElem").addEventListener("click", function() {
// How do I access attr1 from here?
myFunc(); // Says myFunc is not defined.
});
}
}
object.initialize();
How do I access myFunc or attr1 from inside of the anonymous function passed to addEventListener?
One way I can think of is this:
var object = {
attr1 : "hello",
myFunc : function() {
alert(this.attr1); //This should alert "hello"
},
initialize : function() {
myObject = this;
document.getElementById("myElem").addEventListener("click", function() {
// How do I access attr1 from here?
alert(myObject.attr1);
// calling myFunc
myObject.myFunc();
});
}
}
object.initialize();
But is this a good solution?
Also, If I do this:
var object = {
attr1 : "hello",
myFunc : function() {
alert(this.attr1); //This should alert "hello"
},
initialize : function() {
myFunction = this.myFunc;
document.getElementById("myElem").addEventListener("click", function() {
// How do I access attr1 from here?
alert(myObject.attr1);
// calling myFunc
myFunction();
});
}
}
object.initialize();
Then it alerts with "undefined". Which means this.attr1 is undefined.
Why so?
var myObject = thisbind()function:.addEventListener("click" function() {}.bind(this));object.attr1andobject.myFunc?object.myFunc()orobject.attr1