Below code doesn't work, but my idea is to wrap functions into one function, and call the parent function with param. The param will be used by their children function.
_abc(elem){
a(elem){
return elem + 'a';
}
b(elem){
return elem + 'b';
}
}
_abc(elem).b() // doesn't work?
asked Mar 15, 2017 at 4:06
Mellisa
6053 gold badges12 silver badges22 bronze badges
2 Answers 2
You need to mark your functions as functions, remove the inner elem parameters, and return an object containing the functions:
function _abc(elem){
function a(){
return elem + 'a';
}
function b(){
return elem + 'b';
}
return { a:a, b:b };
}
console.log(_abc('hello').b());
Another way to write this this without repeating the function names multiple times:
function _abc(elem){
return {
a: function () {
return elem + 'a';
},
b: function () {
return elem + 'b';
}
};
}
console.log(_abc('hello').b());
And one more, as suggested by @4castle. This one is only supported by JavaScript environments that support EcmaScript 6:
function _abc(elem){
return {
a() {
return elem + 'a';
},
b() {
return elem + 'b';
}
};
}
console.log(_abc('hello').b());
answered Mar 15, 2017 at 4:09
JLRishe
102k19 gold badges139 silver badges171 bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
castletheperson
In ES6 (which is what I suspect they're using given the syntax the OP is attempting), there's a method shorthand for object initializers.
JLRishe
@4castle Thank you. I didn't know about that syntax, but I wouldn't assume that OP is deliberately targeting ES6.
Mellisa
can I do
return {a, b} in es6 instead of return {a:a,b:b}?JLRishe
@Mellisa Yes, you can.
You might me looking for a Java-oriented object, like so:
function _abc(elem)
{
this.elem = elem;
this.a = function()
{
return this.elem + 'a';
}
this.b = function()
{
return this.elem + 'b';
}
}
console.log(new _abc('Hey ').a());
answered Mar 15, 2017 at 4:19
Alvaro Roman
561 silver badge5 bronze badges
2 Comments
Alvaro Roman
Ok, lets name it foo then
Alvaro Roman
I don't really like it but fiiiiiiine, _abc it is
lang-js
_abcis generally referred to as a "constructor function". Does that help you see what it should return?