Ad
  • Default User Avatar
    if (-1 !== handler) 
    

    will always run code

  • Default User Avatar

    That's a great explanation, thank you! I've been trying to examine it very closely and everything seems to have become clear, except for the "unexpected" part.

    fn.apply(fn); // 1002 -> don't expected behaviour

    It may be "unexpected", but I would still like to understand it. Why does obj.fn.val becomes changed at all.....
    Wait, I think I've finally got it right now while I am writing this. Since fn is now 'made' (i think it's a bad word) of obj.fn, we can actually use fn.val, which is by now equal to 1001. When we apply the function itself as this, it of course changes the value which used to be obj.fn.val and is now fn.val. I think I had a wrong understanding that this by default refers to the function itself. But it's not the function, it's the context where the function is triggered.

    Your example is very helpful, thanks again.

  • Default User Avatar

    Oh, yes. Should be if (-1 !== index)
    Thank you(=

  • Custom User Avatar

    In most cases you don't want to do that. If function relay on this in its body (which is equal to window unless function defined in object or "use strict"; is used) you probably will encounter some side effects :) It's safer to pass null and use bind if you need to keep function's current context.

    Perhaps an example will make it clear:

    var obj = {
      val: 0,
      fn: function func() {
        this.val++;
        return this.val;
      }
    }
    window.val = 100;
    obj.fn.val = 1000;
    
    obj.fn(); // 1 -> this === obj
    obj.fn.apply(obj); // 2
    obj.fn.apply(null); // 101
    obj.fn.apply(obj.fn); // 1001
    
    var fn = obj.fn;
    // this now refer to window instance
    fn(); // 102
    fn.apply(null); // 103 -> same as fn()
    fn.apply(fn); // 1002 -> don't expected behaviour
    fn.apply(obj); // 3
    
    var bindedFn = obj.fn.bind(obj);
    // this now is always refer to obj
    bindedFn.apply(obj); // 4
    bindedFn.apply(null); // 5
    bindedFn.apply(obj.fn); // 6
    
  • Default User Avatar

    I have a question. What if in the Event.prototype.emit we apply not null as this, but the function itself? Like this:

    handler.apply(handler, args);

    Can someone explain if this can be better or worse in some cases?

  • Custom User Avatar

    if (-1 !== handler) will always run code