0
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 ?

Sunil Kumar
  • 4,617
  • 2
  • 25
  • 37
  • Because, simplified, it's going to be called as `onclickCallback()` somewhere, which sets `this` to nothing. – deceze Apr 21 '17 at 11:22
  • if you would have search on internet you could find the answer in 2 mins. save the context of this in any variable at starting of your function as you it accordingly. you can use bind or call to call functions in the context you want – A.Sri Apr 21 '17 at 11:22
  • 1
    @deceze _to nothing_??? I think it sets `this` to the element. – ibrahim mahrir Apr 21 '17 at 11:23
  • 2
    Even more simplified: `this` is determined *at call time*. You are not calling the function yourself, so you have no idea what `this` will be set to. – deceze Apr 21 '17 at 11:23
  • @ibrahim Supposedly it's `undefined` according to OP. I have no interest to look it up right now… :) – deceze Apr 21 '17 at 11:24
  • It should point to `window` and not to `undefined` – Felix Apr 21 '17 at 11:26
  • 1
    Basically, Value of `this` is determined how the function is being called! In this case, it is bound to element hence `this` will be element on which click is attached to! – Rayon Apr 21 '17 at 11:27
  • Yes you guys are correct "this" is pointing to element(not to window).may be myObject.myFunction is invoked in some other context of the event listener.Yaa if I do bind context then context will be fixed, even though the function is executed in some other context. – Sunil Kumar Apr 21 '17 at 12:45

1 Answers1

0

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.

ibrahim mahrir
  • 28,583
  • 5
  • 34
  • 61