Home > Back-end >  access a method from an objecy inside of another method in js
access a method from an objecy inside of another method in js

Time:02-26

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 ?

CodePudding user response:

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
}

CodePudding user response:

Maybe this works?

const a = {
  b : () => {console.log("yo")},
  c : () => {a.b()}
}

a.c()

CodePudding user response:

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();

CodePudding user response:

make an actual class:

function A() {
  this.b = () => console.log('yo');
  this.c = () => this.b()
}

var a = new A();

a.c();
  • Related