Why is context different in these two event handlers

|▌冷眼眸甩不掉的悲伤 提交于 2020-01-05 07:08:21

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!