问题
This is a basics question but I cannot figure out why the context ( the 'this' pointer ) is correct in the second event handler and incorrect in the first one.
I have this simple constructor function to create the object myNotifier:
function Notifier ( message ) {
this.message = message;
this.saySomething = function () {
alert( "I say:" + this.message);
}
}
myNotifier = new Notifier(" HELLO!");
Then I use the myNotifier.saySomething()
method as an event handler for CLICK on two buttons:
$(".button1").click( myNotifier.saySomething );
$(".button2").click( function () { myNotifier.saySomething()});
The first one shows: "I say: undefined" The second one shows: "I say: HELLO"
I understand that the context (this )is not the original object when calling the method, but why is it correct when calling inside a function for the second button?
A jsfiddle to test
回答1:
Have a look at MDN's reference for the this keyword: Yes, the context depends on the way you call the method.
If you call the function as a property of an object (like in the handler for button2), that object will be used as the context.
However, if you use it as an event handler (it's the same if wrapped by jQuery), the context of calling the function is the current DOM element, to which the listener is bound. And the button has no property "message", so it will alert undefined
.
Of course, those are not the only alternatives; you might try
var fn = myNotifier.saySomething;
fn(); // context is the global object (window)
or
myNotifier.saySomething.call({message:"buh!"});
:-) - see MDN for explanation and more.
回答2:
for $(".button1").click
the this
keyword is the Dom element with the class button1
.
for $(".button2")
the this
keyword refers to the anonymous function in which you wrapped the call to myNotifier.saySomething()
You can change the context of the function by using the apply() prototype function.
来源:https://stackoverflow.com/questions/12546174/why-is-context-different-in-these-two-event-handlers