Skip to content

Instantly share code, notes, and snippets.

@HankZhi
Created December 27, 2021 08:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save HankZhi/bb39344d164cd6c88f1b2b2ebec3d60f to your computer and use it in GitHub Desktop.
Save HankZhi/bb39344d164cd6c88f1b2b2ebec3d60f to your computer and use it in GitHub Desktop.
js function's "this"
const obj = {
child: {
child: {
value: 1,
fn: function () {
console.log(this.value)
}
}
}
}
// normal usage
obj.child.child.fn();
// optional chaining usage
obj?.child?.child?.fn?.()
// with eslint below version 7.5.0, will trigger rule `no-used-expression`, change code to fix it, then touch a `this` error
const fn = obj?.child?.child?.fn;
if (fn) {
fn(); // log undefined
}
// use `call`
const fn = obj?.child?.child?.fn;
if (fn) {
fn.call(obj?.child?.child);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment