[CODE GOLF] Avoiding use of 'this'

Watching a presentation by Douglas Crockford he suggested as an exercise to avoid using this inside Javascript programs.

This got me thinking. How to not use this in day to day ember code. I find myself using it all the time, perhaps almost ritualistically.

Would love to see folk’s before and after refactor examples following a no this principle.

Start with an example

Person = Ember.Object.extend({
  // these will be supplied by `create`
  firstName: null,
  lastName: null,

  fullName: Ember.computed('firstName', 'lastName', function() {
    return `${this.get('firstName')} ${this.get('lastName')}`;
  })
});

I am not even sure how to remove this.get pattern inside that computed property. Thoughts?

I don’t really see that applicable that way. An object model with no use of this would most probably rely on creating closures and dynamically letling methods close over some variable it would use as a replacement to this.

function createThing(options) {
    const self = {
        msg: options.msg
    };
    self.sayHi = function () {
        window.alert(self.msg);
    };
    return self;
}
const obj = createThing({msg: 'Hello'});
obj.sayHi();    // popup 'Hello'

It has some advantages. For instance, you can close over variables directly in createThing, effectively making them inaccessible outside of the methods, acting as “private” variables. And some drawbacks too, such as instanceof not working and inheritance in general being more complicated (though feasible).

You won’t be doing that in Ember. For starters, even if you did, Ember itself uses this and a prototype-based object model, defeating any attempt you will make.

Though interesting, the video you linked is only relevant to a very specific context: you want to load and execute untrusted JS code. And to do that, the solution he used is to bar ads’ untrusted JS code from using this. Now, you won’t be loading an Ember application as an ad, will you?

1 Like

Yes, this was why I was asking this question. Thanks for this response.

Certainly not suggesting it would be practical let alone even possible within the Ember system.

With the Ember.Object approach, you of course cannot avoid the use of this and should not even try. Ember uses a sort of OOP approach which is predicated on “classes” and subclassing. Crockford’s discussion of approaches not using this is predicated on NOT adopting this kind of “classic” OOP approach.