0

I'm reading JSIS article http://javascriptissexy.com/javascript-apply-call-and-bind-methods-are-essential-for-javascript-professionals/ here's the example where I want something clear.

The example method 'clickhandler' uses this keyword to refer to the user object, but this won't work the work around is to use prototype bind method.. but what is the advantage of doing this stuff instead of just saying user.data directly instead of using this keyword.

//<button>Get Random Person</button>
//<input type="text">


var user = {
    data :[
        {name:"T. Woods", age:37},
        {name:"P. Mickelson", age:43}
    ],
    clickHandler:function (event) {
        var randomNum = ((Math.random () * 2 | 0) + 1) - 1; // random number between 0 and 1
        // This line is adding a random person from the data array to the text field
        $ ("input").val (this.data[randomNum].name + " " + this.data[randomNum].age);
    }
}

// Assign an eventHandler to the button's click event
$ ("button").click (user.clickHandler);
Harman
  • 298
  • 1
  • 13
null
  • 1,062
  • 1
  • 9
  • 21
  • I'm pretty sure the `this` magic is partly jQuery binding context in it's handlers. – zero298 Oct 12 '17 at 15:08
  • Yes, just referring to `user` instead of `this` and binding it would be a much simpler solution here. The only drawback might be that you cannot rename the `user` variable as easily any more, having more references to it. – Bergi Oct 12 '17 at 15:10

0 Answers0