See my code
http://jsfiddle.net/kxATT/3/
function byId(id) {
if (id) {
return document.getElementById(id);
} else {
return null;
}
}
function setAttr(elm, attr, value) {
elm.setAttribute(attr, value);
}
var app = {
id: 12,
fn: function () {
alert(this.id);
}
};
function init() {
setAttr(byId('txt'), 'onclick', 'app.fn()');
byId('txt1').addEventListener('click', app.fn, true);
}
When the first box is clicked,it alerts 12. And for the second box it alers txt1. Obviously in both cases although I’m calling the same function, this refers to different objects. I’ve heared that, for input elements,the element’s object itself is passed to the function and reffered as this inside the event handler function. If so why is it not true when events are added using setAttribute.
When you assign a string to
onclick, you’re basically creating the body of a function; the browser supplies the function, e.g. your string"app.fn()"becomes:When you assign a function reference via
addEventListener, as with any time you use a function reference with JavaScript, it’s just a function reference; there is no object information.thisin JavaScript is set entirely by how a function is called, not where it’s defined.If you’re using an ECMAScript5-enabled environment (or using an ES5 shim), you can solve this using
Function#bind:Otherwise, you can solve it by supplying the function that the browser provides in the string case yourself:
More reading:
this