var myObject = {
myFunction : function (){
var randomizer = Math.random() * 10;
if(randomizer > 5){
this.myGreaterThanFunction();
}else{
this.myLesserThanFunction();
}
},
myGreaterThanFunction: function (){
document.getElementById("result").innerHTML = "randomizer number is greater than 5";
},
myLesserThanFunction: function (){
document.getElementById("result").innerHTML = "randomizer number is less than 5";
}
};
myObject.myFunction(); // In this case "this" will points to myObject.hence "this" works here as expected.
document.getElementById("button2").onclick = myObject.myFunction.bind(myObject); // In this case, as we are binding myObject to myFunction then "this" will points to myObject.and then "this" works as expected.
document.getElementById("button1").onclick = myObject.myFunction; // In this case,I expect "this" should points to myObject.But I am getting this as undefined.why ?
Because the event listener get bound to the element (this
inside the event listener will refer to the element that fired the event). Unless, of course, the event listener get explicitly bound to another thing using .bind
.