Skip to content Skip to sidebar Skip to footer

Why Is `this` Not Equal To `object` And Why Is Property `undefined`?

This object implements a pattern to provide event listeners. It works in at least IE 11 and Chrome. But I don't understand why and I have 2 questions. In the keypress event listen

Solution 1:

(I'm using call rather than bind so the code works with older browsers.)

Why? bind is a lot simpler apparently. If you want it to work with older browsers, just include this simple polyfill somewhere in your code.

What changes have to be made to the pattern for onCustomKeypress to have access to the event interface / object?

None. The problem is still your addEvent function, which might now invoke the callback with the correct context but without the arguments. Two solutions:

  • Use the arguments object and apply instead:

    …(…, function() {
        callback.apply(caller, arguments);
    } …
    
  • Just pass the event argument to call - it takes any number of normal arguments after the context:

    MyObj.prototype.addEvent = function(event, callback, caller) {
        'use strict';
        if (typeofwindow.addEventListener === 'function') {
            this.element.addEventListener(event, function(e) {
                callback.call(caller, e);
            }, false);
        } else {
            // for older versions of IE, order of test is importantthis.element.attachEvent('on' + event, function() {
                callback.call(caller, window.event);
            });
        }
    };
    

Post a Comment for "Why Is `this` Not Equal To `object` And Why Is Property `undefined`?"