passing this object as argument in onChange event?

emilly picture emilly · Aug 8, 2013 · Viewed 45.6k times · Source

I want to make an eventHandler that passes "this" object as parameter. I tried this

 <select id="customer" onchange="custChange(this);">

it works fine and get the the dom object on which on change even was called.

But as per my understanding this should not work as first argument is expected as "event" (not the "this" object )in event handler method like below

  <select id="customer" onchange="custChange(event);">

can we pass any argument(this or event) in eventHandler method provide their name is correct or first argument will always be considered as event object?

Answer

Felix Kling picture Felix Kling · Aug 8, 2013

You defined custChange and more importantly: you are calling it. Hence you can decide for yourself which arguments it should accept and in which order. Only for functions that are not called by you, you have to pay attention to the order of arguments.

But if you want to define custChange so that it is compatible with other ways of binding event handlers, i.e.

function custChange(event) {
    // `this` refers to the DOM element
}

then you can call it with

custChange.call(this, event);