Created
November 21, 2018 21:54
-
-
Save adambankin/677f2b534de74846d0434e3f0a189de5 to your computer and use it in GitHub Desktop.
Using `this` with destructuring
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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' })); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 actualgetter
, it would solve thethis
issue*:*with the caveat that you can't apply another context, but maybe that's not needed?