0

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?
1
  • Your _abc is generally referred to as a "constructor function". Does that help you see what it should return? Commented Mar 15, 2017 at 4:11

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

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.
@4castle Thank you. I didn't know about that syntax, but I wouldn't assume that OP is deliberately targeting ES6.
can I do return {a, b} in es6 instead of return {a:a,b:b}?
@Mellisa Yes, you can.
0

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

2 Comments

Ok, lets name it foo then
I don't really like it but fiiiiiiine, _abc it is

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.