Created
December 27, 2021 08:22
-
-
Save HankZhi/bb39344d164cd6c88f1b2b2ebec3d60f to your computer and use it in GitHub Desktop.
js function's "this"
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
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