How can I access a sibling property from a method in Javascript? It seems like a simple thing to want to do, but I haven't found a way. Specifically, consider the following code.
let f = {
a: 3,
printMyBrother() { console.log(X) }
}.printMyBrother
f()
What must I change X
to in the above code, in order to programatically log "3" on the console?
You can do it if you change your code a little bit:
This is an example of different ways that this would work. The reason it works this way is due to interesting rules of javascript's this
.
let f = { a: 3, printMyBrother(message) { console.log(message, this.a) } } let printMyBrother = f.printMyBrother; console.group('function'); console.log('function'); f.printMyBrother('function call') // The printMyBrother won't work alone without being bound printMyBrother('unbound function call'); // Bind printMyBrother variable to always refer to f printMyBrother = printMyBrother.bind(f); printMyBrother('bound function call') console.groupEnd(); class ClassF { a = 3; // This is unbound to the class by default // because it's not an arrow function // You can bind it in the constructor manually, however printMyBrotherUnbound(message) { console.log('classF', message, this.a) }; // This is bound to the class by default // because it's an arrow function // This should work in all major browsers (besides IE) printMyBrotherBound = (message) => { console.log('classF', message, this.a) } } let classF = new ClassF(); console.group('Class Method') console.log('Class Method') printMyBrother = classF.printMyBrotherUnbound; classF.printMyBrotherUnbound('in class'); try { printMyBrother('unbound'); } catch (error) { console.log('unbound class function errors out because this is undefined'); } console.groupEnd() console.group('Class Arrow Function'); console.log('Class Arrow Function'); printMyBrother = classF.printMyBrotherBound; classF.printMyBrotherBound('arrow function'); printMyBrother('unbound arrow function'); console.groupEnd();
Some resources on the this
keyword in JavaScript:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.