I'm reading a great article on this
in JavaScript. The author says that the following code is bad:
Cart = {
items: [1,4,2],
onClick: function () {
// Do something with this.items.
}
}
$("#mybutton").click(Cart.onClick);
He says that the click
event doesn't know about the Cart
object when calling onClick, therefore this.items
won't be the [1,4,2]
array that I expect it to be.
The author goes on to say that this code creates a closure and fixes it but I don't understand how the following code fixes the problem.
$("#mybutton").click(function () { Cart.onClick() });
1) In what context (if not Cart
) does this
thing we're in if we use the first example.
2) Why does the second example fix the problem?