You might think of something like this:
let obj={
childone: (value) => {
return value+1;
},
childtwo: (value) => {
return value+3;
},
childsingle: obj.childone
}
};
But that doesn't work. You have to do it in two steps.
The way the assign operator (=
) works, is as follows. It uses the right side of the operator, computes its value and assigns that value (which is a reference to an object in your case) to the variable on the left side.
So at the time the right hand side of the assign operator is assembled, the obj
variable is not existent. So you will get an error.
This will also not work
let obj={
childone: (value) => {
return value+1;
},
childtwo: (value) => {
return value+3;
},
childsingle: this.childone
}
};
because this
will not refer to the current object.
This will not work, because childone
is not defined
let obj={
childone: (value) => {
return value+1;
},
childtwo: (value) => {
return value+3;
},
childsingle: childone
}
};
This is the way to go:
let obj={
childone: (value) => {
return value+1;
},
childtwo: (value) => {
return value+3;
},
};
obj.childsingle = obj.childone;
But beware, if you are planning to change the childone
function and think that the childsingle
function will change as well, that is not true.
Before changing childone
, we have two keys of the object (childone and childsingle) that are references to the same function. But childone and childsingle are not related elsewise. If you change chilone this will be a reference to a new function and childsingle will remain the same old function