'Access a method from an object inside of another method in JavaScript
imagine having this object :
var a = {
b : () => console.log("yo"),
c : () => b()
}
How can I execute the b function calling the c one ? the syntax above doesn't work... Do you have an idea ?
Solution 1:[1]
var a = {
b : () => console.log("yo"),
c : () => a.b() // reference to the object
}
or
var a = {
b : () => console.log("yo"),
c : function () {return this.b()} // use function syntax instead of lambda to gain a reference to the object on which c() is called
}
Solution 2:[2]
Maybe this works?
const a = {
b : () => {console.log("yo")},
c : () => {a.b()}
}
a.c()
Solution 3:[3]
Instead of arrow functions use non-arrow functions, and then this will be available, if the method is called in the usual way:
var a = {
b() { console.log("yo") },
c() { return this.b() }
}
a.c();
Solution 4:[4]
make an actual class:
function A() {
this.b = () => console.log('yo');
this.c = () => this.b()
}
var a = new A();
a.c();
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Mihályi Zoltán |
| Solution 2 | ask4you |
| Solution 3 | trincot |
| Solution 4 | bryan60 |
