News for hackers. Stuff that matters.
Re:‘This’ in JavaScript by rjeli on Thursday August 03, 2017 @01:00AM (#14917058)
I don't like the explanation as a set of piecewise cases. this just refers to the current object context. this refers to the window at the top level because you're operating within `window`. There aren't "simple functions" and "object constructor functions", just functions, and the `new` keyword executes the function within the context of a new object. Event listeners are not a special case, it's just that the callback is executed from the context of the event -- which makes the difference between `function (e) { this }` and `e => this` much easier to understand.
Re:‘This’ in JavaScript by fenomas on Thursday August 03, 2017 @01:45AM (#14917220)
I agree. The key to grokking this is the difference between a function's execution context and its lexical scope. If you don't explain that I don't think you've explained anything, and if you do then there's no need to think about separate cases like the article suggests.
Re:‘This’ in JavaScript by Joeri on Thursday August 03, 2017 @06:55AM (#14918485)
If you think of javascript code like an english sentence, then the function is the verb, the context (this) is the subject and the scope (arguments, closed over variables) are the nouns.
Re:‘This’ in JavaScript by rippeltippel on Thursday August 03, 2017 @08:09AM (#14918820)
s/nouns/objects/g (then the analogy works for me)
Re:‘This’ in JavaScript by carussell on Thursday August 03, 2017 @03:20AM (#14917581)
The unfortunate thing about the lengths people go to in order to try to "fix" `this` in event handlers is that it wouldn't be a problem if people just implemented the event listener interface correctly.

PSA Don't do this:

  proto.foo = function() {
    /* ... */
    var self = this;
    element.addEventListener("click", (function(event) {
      self.iHaveAnUnhealthyObsessionWithLambdas(event.target);
    }));
  }

  proto.iHaveAnUnhealthyObsessionWithLamdas = function(clicked) {
    /* do something with clicked element `clicked` */
  }
Do this instead:

  proto.foo = function() {
    /* ... */
    element.addEventListener("click", this);
  }

  proto.handleEvent = function(event) {
    /* do something with clicked element `event.target` */
  }
Re:‘This’ in JavaScript by amelius on Thursday August 03, 2017 @05:16AM (#14918083)
The problem is that the approach is different depending on context. You are making use of the assumption that the addEventListener function knows to call the "handleEvent" method of the object in the second argument, and give it a proper "this" object. That's a big assumption, which should be documented in the code.

The code using "self" doesn't have this problem; it's more self-contained so to speak (no pun intended).

Re:‘This’ in JavaScript by carussell on Thursday August 03, 2017 @09:21AM (#14919269)
> That's a big assumption

No, it's not. At all. It's part of the DOM Level 2 standard that specifies what `addEventListener` does and has been for going on 20 years.

https://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-...

Re:‘This’ in JavaScript by amelius on Thursday August 03, 2017 @02:36PM (#14922392)
Well I don't see it used in a lot of code, so in that respect I think it is obscure. Also, using the "self" approach allows one to lexically bind to the enclosing scope, which aligns nicely with how most functional programmers think.
Re:‘This’ in JavaScript by carussell on Saturday August 05, 2017 @01:01PM (#14936631)
> Well I don't see it used in a lot of code, so in that respect I think it is obscure.

You just moved the goalposts.

Re:‘This’ in JavaScript by kitd on Thursday August 03, 2017 @06:23AM (#14918352)
Agreed. Much prefer 'var self = this' style. Keep the model transparent for future maintenance.

One time I don't is in Jasmine, where they explicitly state that 'this' is shared across all 'beforeEach', 'it' and 'afterEach' calls. Which backs up your first point.

Re:‘This’ in JavaScript by scruple on Thursday August 03, 2017 @12:39PM (#14921112)
This is where I've landed with the JavaScript that I write. It keeps things relatively sane, at least better than the other approaches I've tried.
Re:‘This’ in JavaScript by nkozyra on Thursday August 03, 2017 @07:51AM (#14918724)
I thought self had gone out of favor due to its relatively new global purpose.
Re:‘This’ in JavaScript by kitd on Thursday August 03, 2017 @08:40AM (#14918994)
ok, call it something else. I meant to say, save away the current ref to 'this'.
Re:‘This’ in JavaScript by icebraining on Thursday August 03, 2017 @03:31AM (#14917637)
But then if you're listening to multiple events, won't you have to try to disambiguate after the fact in handleEvent()?
Re:‘This’ in JavaScript by wiredearp on Thursday August 03, 2017 @10:37AM (#14919939)
That's the fun part, because here you can code your event handling to read something more like a state machine. Here's a quick example in bogus code, adding and removing event listeners as we go along (and without keeping reference to all the callback functions):

  class ElementDragger {
    constructor(elm) {
      elm.addEventListener('mousedown', this);
    }
    handleEvent(e) {
      const elm = e.target;
      switch(e.type) {
        case 'mousedown':
          elm.removeEventListener('mousedown', this).
          elm.addEventListener('mousemove', this);
          elm.addEventListener('mouseup', this);
          break;
        case 'mousemove':
          elm.style.left = e.clientX + 'px';
          break;
        case 'mouseup':
          elm.removeEventListener('mousedown', this);
          elm.removeEventListener('mouseup', this);
          elm.addEventListener('mousedown', this);
          break;
      }
    }
  }
Re:‘This’ in JavaScript by richthegeek on Thursday August 03, 2017 @11:30AM (#14920423)
That seems complicated, fragile, and bad for performance in a DOM. Event bindings are slow (or at least, used to be).

I don't know the purpose unbinding mousedown on mousedown - it only fires once per mousedown doesn't it?

Why not just stick with `elm.addEventListener('mousedown', this.handleMouseDown.bind(this))`? Where's the benefit other than making things more verbose?

Re:‘This’ in JavaScript by rayshan on Thursday August 03, 2017 @11:51AM (#14920614)
Bind is less performant, because bind creates a new function with new context. At the framework level, bind is avoided at all costs. @wiredearp's approach is correct, because it only adds a single event listener, everything else is conditional.
Re:‘This’ in JavaScript by carussell on Thursday August 03, 2017 @12:00PM (#14920709)
If you think the above code has bad performance because "event bindings are slow" then your preferred form using `bind` is going to have all of that and more; it sidesteps nothing (except extremely fast switch case matching) and only adds overhead, both in runtime and memory costs.

> Where's the benefit other than making things more verbose?

To be clear what you're asking, are you saying that:

    elm.addEventListener('mousedown', this);
... is more verbose than:

    elm.addEventListener('mousedown', this.handleMouseDown.bind(this))
Re:‘This’ in JavaScript by wiredearp on Thursday August 03, 2017 @12:37PM (#14921084)
If you plan to remove that event listener later on, you would need to go full verbose.

  this._callback = this.handleMouseDown.bind(this);
  elm.addEventListener('mousedown', this._callback);
  elm.removeEventListener('mousedown', this._callback);
  this._callback = null;
Compared to:

  elm.addEventListener('mousedown', this);
  elm.removeEventListener('mousedown', this);
  
@richthegeek I removed that event listener in my example to illustrate how easy it is, there was otherwise no good reason for it.
Re:‘This’ in JavaScript by yarrel on Thursday August 03, 2017 @12:22PM (#14920958)
No, that a switch statement is more verbose than a single function.

Switch statements in OOP are a sign that something is wrong.

Re:‘This’ in JavaScript by extrapickles on Thursday August 03, 2017 @01:10PM (#14921467)
Switch statements are fine for simple tasks like the one in the example, especially earlier in a project where you do not know what you need in the future. You can always switch it to the correct pattern in version 2 as that way its better understood what hidden needs the code in question has, thus making it easy to pick a good OOP patern to replace it.

Then again, my jugment might be colored by working on codebases that are >21 years old.

Re:‘This’ in JavaScript by wiredearp on Thursday August 03, 2017 @12:52PM (#14921250)
It's however easy to read and that feels good if not right, since the common solutions to this imagined problem require substantial mental overhead as seen on https://hackernoon.com/rethinking-javascript-eliminate-the-s.... To promote "single functions" we could:

  handleEvent(e) {
    this[e.type](e, e.target);
  }
  mousemove(e, elm) {
    elm.style.left = e.clientX + 'px';
  }
... but then the discussion would almost certainly revolve around this questionable decision instead of the original topic.
Re:‘This’ in JavaScript by carussell on Thursday August 03, 2017 @02:46PM (#14922488)
> No, that a switch statement is more verbose than a single function.

You're vacillating and applying an inconsistent standard. The switch statement is used where multiple listeners are being attached, therefore it wouldn't work with your "single function". You'd need multiple functions.

Give any example passing functions directly as the callback to `addEventListener` to demonstrate your case, please. The equivalent version that simply implements DOMEventListener will be less verbose, be lighter on resources (both with memory use and with runtime), and have no need for any this-binding workaround weirdness.

Re:‘This’ in JavaScript by janci on Thursday August 03, 2017 @03:49AM (#14917729)
Better yet element.addEventListener("click", self.handleClick.bind(this))
Re:‘This’ in JavaScript by rayshan on Thursday August 03, 2017 @11:49AM (#14920585)
This is less performant, because bind creates a new function with new context. At the framework level, bind is avoided at all costs.
Re:‘This’ in JavaScript by janci on Friday August 04, 2017 @12:02PM (#14929670)
The overhead is not important, if you bind once. It becomes problem, if you do it too often, like in react render function.
Re:‘This’ in JavaScript by thousande on Thursday August 03, 2017 @04:50AM (#14917979)
Today I learned

In general, a good practice is to avoid anonymous functions for the listener else it is not possible to remove the event later.

Re:‘This’ in JavaScript by wiredearp on Thursday August 03, 2017 @10:24AM (#14919822)
I guess the function could still be anonymous, but you will at least need to keep it assigned to some variable or property name. If you make use of the `handleEvent` pattern that @carussell suggested, you can however avoid having to keep track of all these callback functions since the listener can always be removed by passing `this` a second time:

['click', 'focus', 'blur'].forEach(type => elm.removeEventListener(type, this));

Re:‘This’ in JavaScript by sheldor on Thursday August 03, 2017 @02:05AM (#14917305)
> I don't like the explanation as a set of piecewise cases

We don't like it and it's redundant. One should learn the principles and return to this article to read it as a quiz and find out whether he got it or not.

Books like the excellent Javascript Allonge (free to read on leanpub) do a great job on explaining the context. If you need more hardcore stuff, "You don't know JS" will fit you better.

(Disclaimer: I'm not affiliated with any of the recommended books or their authors or leanpub or whatever.They just helped me a lot; and still do from time to time)

Re:‘This’ in JavaScript by abritinthebay on Thursday August 03, 2017 @01:25AM (#14917143)
Agreed. It’s extremely poorly explained and quite misleading
Re:‘This’ in JavaScript by pier25 on Thursday August 03, 2017 @12:38PM (#14921101)
> this just refers to the current object context

Exactly.

"If you can't explain it simply, you don't understand it well enough."

Albert Einstein

Re:‘This’ in JavaScript by v413 on Thursday August 03, 2017 @05:36AM (#14918170)
As an event listener "function(e) {this}" is not the same as "(e) => this". With the regular function "this" points to the element on which the event listener was attached to while with the arrow function "this" points to the context (i.e. "this") of its lexical environment.
Re:‘This’ in JavaScript by christophilus on Thursday August 03, 2017 @05:46AM (#14918207)
That's what the OP was saying.
Re:‘This’ in JavaScript by zappo2938 on Thursday August 03, 2017 @11:15PM (#14926071)
This refers the to the object left of the .