简体   繁体   English

为什么这两个事件处理程序中的上下文不同

[英]Why is context different in these two event handlers

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. 这是一个基本问题,但我无法弄清楚为什么上下文('this'指针)在第二个事件处理程序中是正确的而在第一个事件处理程序中是不正确的。

I have this simple constructor function to create the object myNotifier: 我有这个简单的构造函数来创建对象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: 然后我使用myNotifier.saySomething()方法作为CLICK的事件处理程序在两个按钮上:

$(".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? 我理解上下文(this)在调用方法时不是原始对象,但为什么在第二个按钮的函数内部调用时它是正确的?

A jsfiddle to test 一个jsfiddle来测试

Have a look at MDN's reference for the this keyword : Yes, the context depends on the way you call the method. 看看MDN对this关键字的引用 :是的,上下文取决于您调用方法的方式。

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. 如果将该函数作为对象的属性调用(如在button2的处理程序中),则该对象将用作上下文。

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. 但是,如果将它用作事件处理程序(如果由jQuery包装则相同),则调用该函数的上下文是侦听器绑定到的当前DOM元素。 And the button has no property "message", so it will alert undefined . 并且该按钮没有属性“消息”,因此它将提示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. :-) - 请参阅MDN以获取解释等。

for $(".button1").click the this keyword is the Dom element with the class button1 . for $(".button1").click this关键字是带有类button1的Dom元素。

for $(".button2") the this keyword refers to the anonymous function in which you wrapped the call to myNotifier.saySomething() 对于$(".button2")this关键字引用匿名函数,在其中包含对myNotifier.saySomething()的调用

You can change the context of the function by using the apply() prototype function. 您可以使用apply()原型函数更改函数的上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM