Skip to content

Instantly share code, notes, and snippets.

@adambankin
Created November 21, 2018 21:54
Show Gist options
  • Save adambankin/677f2b534de74846d0434e3f0a189de5 to your computer and use it in GitHub Desktop.
Save adambankin/677f2b534de74846d0434e3f0a189de5 to your computer and use it in GitHub Desktop.
Using `this` with destructuring
function Item ({ name, id }) {
this.id = id;
this.name = name;
}
Item.prototype.getName = function () {
return this.name;
};
function checkThis1 ({ getName }) {
console.log(getName());
} // the context of `this` is lost by using destructuring so when the `getName` method is called
// its `this` will be the `this` of the context of `checkThis1`
function checkThis2 (item) {
console.log(item.getName());
} // will print `"Jeff"` because the context of the `this` is an instance of Item
function checkThis3 ({ getName }) {
console.log(getName.call({ name: 'Not Jeff' }));
} // will print `"Not Jeff"` because the `this` is lost by destructuring and the `.call()` creates
// the context for the `this` in the subsequent call to `.getName()`
checkThis1(new Item({ id: 1, name: 'Geoff' }));
checkThis2(new Item({ id: 2, name: 'Jeff' }));
checkThis3(new Item({ id: 3, name: 'Djeoff' }));
@sassomedia
Copy link

sassomedia commented Nov 22, 2018

Modified this slightly to have an actual private property that wouldn't be available without accessing a function. Otherwise the setup is the same. If you turn getName into an actual getter, it would solve the this issue*:

class Item {
  constructor({ first, last }) {
    this.first = first;
    this.last = last;
  }

  get name() {
    return this.first && this.last ? `${this.first} ${this.last}` : undefined;
  }
}

function checkThis1({ name = 'Tomasz Piorek' }) {
  console.log(name);
}

function checkThis2(item) {
  console.log(item.name);
}

function checkThis3({ name }) {
  console.log(name.call({ first: 'Not', last: 'Terrence' }));// throws error since
  // getters are not technically a function but rather a pseudo-property
}

checkThis1(new Item({ first: 'Adam', last: 'Bankin' }));// prints "Adam Bankin"
checkThis1(new Item({ name: 'Adam Bankin' }));// prints "Tomasz Piorek"
checkThis2(new Item({ first: 'Jason', last: 'Delia' }));// prints "Jason Delia"
checkThis3(new Item({ first: 'Terrence', last: 'Keane' }));// throws error, sorry Terrence XD

*with the caveat that you can't apply another context, but maybe that's not needed?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment