0

I am trying to add an inner function to the function and invoking that child function from another function.

My function driver code is as below which i cannot modify:

const obj =  function1();
obj.method1(soemobject);

The definition for the function1() which is already present is as below:

function function1(){

}

What I want to achieve is adding a method inside function1 so that i can call it from another function:

function function1(){
    function method1(item){
       console.log(item)
}
}

The error I am getting is:

enter image description here

with the code chunk

function function1(){
        function method1(item){
           console.log(item)
    }
    this.method1 = method1
    }

and

enter image description here

with the code chunk

 function function1(){
        function method1(item){
           console.log(item)
    }
    }

What I have tried so far is:

  1. Making it a constructive function: But as the driver code cannot be modified, this won't work as it needs to be called with a new keyword.
  2. Tried accessing function1's properties using this keyword, no luck.
0

1 Answer 1

2

Define function1 like this:

 function function1(){
      return {
       method1: function(item){
           console.log(item)
       }
      } 
    }

The result from calling function1 is stored as obj

const obj =  function1();

method1 is called on obj

obj.method1(soemobject);

obj in this case is:

{
    method1: function(item){
        console.log(item)
    }
} 
Sign up to request clarification or add additional context in comments.

2 Comments

These worked, Thank you. The question is I want to return an array instead of console log it? and along with method1, I also have a few more methods to invoke from the same function, will the syntax be the same? separated by ","?
You can return an array or anything from within method1. method1: function(item){ return [item] } Yes, adding another function in the returned object obj along with method1 is just the same syntax separated by, : return { method1: function(item){ console.log(item) }, method2:function(){} } If it worked, please accept the Answer:)

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.