Suppose I have a javascript class like this:
class MyClass {
constructor (a) {
this.a = a;
}
foo() {
// do something
}
bar() {
const baz = this.foo();
// do something with baz
}
}
In the bar()
function I can call the foo()
function using this
.
Is it possible to do this using an object instead of a class? For example:
const myObj = (a) => {
return {
foo: () => {
// do something
},
bar: () => {
const baz = foo(); // this doesn't work
const baz = myObj.foo() // this doesn't work either
// do something with baz
}
}
}
A solution I found is to define foo
and bar
outside of the object and then assign them to the object afterwards, but it doesn't feel right:
const myObj = (a) => {
const foo = () => {
// do something
};
const bar = () => {
const baz = foo();
// do something with baz
};
return { foo, bar };
}
Is there a way to reference an object's own property from inside of the object?
Edit: Thanks to the responders, an easy solution is to not use arrow functions, and then you can use this
:
const myObj = (a) => {
return {
foo: function () {
// do something
},
bar: function () {
const baz = this.foo() // this works!
// do something with baz
}
}
}