[Javascript] Comparing objects

liorean liorean at gmail.com
Tue May 16 15:43:19 CDT 2006


On 16/05/06, Bill Moseley <moseley at hank.org> wrote:
> Maybe this is my lack of understanding of "this".

Okay, then I'll try to explain it. In code, of course :)

    var
        global=this, // initialised in the global scope so is the global object
        o={},
        elm=/*code to get the element used for the event registrations*/,
        fn=function(){
            alert(this===o?'o':this===global?'global':this===elm?'elm':this;)};

    fn(); // ==> 'global'
    // function calls use the global object as this

    o.md=fn;
    o.md(); // ==> 'o'
    // method calls use the bound object as this

    o['md'](); // ==> 'o'
    // independent of how the method was referenced

    fn=o.md;
    fn(); // ==> 'global'
    // just to prove that it's how you're calling it that matters

    fn.call(o); // ==> 'o'
    // because Function.prototype.call takes a this object as first argument

    fn.apply(o); // ==> 'o'
    // same goes for Function.prototype.apply



This pattern should explain how it normally works. So, how does it
work when you add something not included in the core language such as
events?



    elm.onevent=fn;
    elm['onevent']=fn; // event triggered --> 'elm'
    // If event triggers, fn will be called with elm as it's this object.
    // "Why, when there's no 'elm.onclick()' in there?" you might ask.
    // The answer is: Because that's what Netscape originally did.

    elm.attachEvent('onevent',fn); // event triggered --> 'global'
    // Microsoft proprietary event registration, fn is not a method of elm and
    // attachEvent does not make fn take elm as it's this object, so this will
    // be the global object.

    elm.addEventListener('event',fn,false) // event triggered -->
impl. dependant
    // W3C event registration. Does not deal with the this object, so actually
    // you cannot rely on it being 'elm' in this case. But you
shouldn't have to use
    // this anyway, since you have 'ev.target' and 'ev.currentTarget' in all
    // implementations of addEventListener that I know of.


And before you ask, yes, there is at least one implementation of
addEventListener I know of that doesn't set the this object to the
element it's registering the object on. That implementation is a
fringe browser, MSN/OSX, but if one implementation does it that way I
would expect there to be more implementations doing the same.
-- 
David "liorean" Andersson
<uri:http://liorean.web-graphics.com/>



More information about the Javascript mailing list