开发者

Why in .NET this in button handler references parent instead of button?

In javascript DOM this refers to the element clicked which seems more logical than in .NET where this refers to the parent. Why this choice?

The button is also a class. If it was truly OOP it would consider button as first class citizen also. So It's not a question of paradigm here it's rather a question of imple开发者_如何学编程mentation. My hypothesis is that was probably easier for MS to do so because the physical module exists for parent not for child.

But for us it is a pity since you have to cope with this sender which seems as it is foreign to the button whereas it is himself !


They are different systems and different paradigms.

In .NET, your handlers are passed a "sender" argument which contains the object. The handlers reside in the form object or user control, so "this" refer to that class (if you do a double-click type of adding a handler). If you manually created the handler, then it can be part of any object (not necessarily the form object), and "this" will map to different things. .NET events are also not bubbled or captured.

In DOM, your handlers are not passed a "sender" argument. However, "this" refers to the object. In DOM, events can bubble or captured.

There is no reason why the designer of JavaScript cannot provide a "sender" argument though, and map "this" back to the object holding the handler. In my opinion, these were just historical choices being made when the world was much simpler.


In C# the handlers are methods of the Form object and thus this also references this object.

However, I think you can use one of the handler's arguments to get the element related to the event.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜