If I have a object, with a function that captures every form on the page as an array:
var object =
{
var forms = document.getElementsByTagName("form");
And I add an event listener to it (W3C DOM 2 Event Model, I don’t care about IE for this example):
addEventListener = function(target, type, listener)
{
target.addEventListener(type, listener, false);
};
And I call (normally a loop, but lets just take one example):
addEventListener(forms[i], "change", changeListener);
And changeListener is equal to:
changeListener: function(event)
{
updateDependents(this);
}
And updateDependents equals:
updateDependents: function(form)
{
...
}
};
can someone explain to me the progression of arguments (i.e. what “this” and “event” are equal to)?
To me, it looks like:
For the form in question (forms[i]), an event listener is being added based upon a “change” event, and the action to be taken is “changeListener”.
changeListener takes an argument of (event), so it must be referencing potential event that forms[i] has(?). [not sure about this]
It then calls “updateDependents(this)”… what is the “this” here? Is it the form that is identified in the “target” argument of the “addEventListener” method, or is it the event argument that exists within the “changeListener(event)” method? [can someone please explain why it would be one over the other?]
Note: I’m obviously confused, so I apologize for any stupidity. Also, this is an excerpt from “Simply Javascript” by Sitepoint.
Cheers,
Sapiensgladio
In JS
thisonly gets a value in a few ways:When calling
someObj.method(), thenthis === someObjCalling
method.call(someObj, ...), thenthis === someObj, and likewise formethod.apply(someObj, args)In Javascript 1.8.5 / ES5, by using
Function.prototype.bind()If a method is invoked simply as
method()thenthis === window(or whatever the global object is if you’re not in a browser).DOM2’s
addEventListener()uses #2 above and setsthisto be the element from which the event was fired.