-2
   function a(){
        this.i = 10,
         function b(){
            console.log("Regular function ",this.i, this)
        }
    }
    

Here I want to call function b

2
  • 1
    Just call it as b() from within a. If you want to call it from outside of a. then assign it to a with this.b = b; then you can do var foo = new a(); foo.b(); Commented Dec 23, 2020 at 15:45
  • Answer is you don't.... Commented Dec 23, 2020 at 15:46

2 Answers 2

0

Because of the use of this within the function, you need to call the a function as a "constructor function" (with the new keyword) or invoke it with call(), apply(), or bind() so that you can specify context for this.

And, because the b function uses the context of a, it should be either returned from the parent or declared as an instance method of a with this.b = function()...

function a() {
  this.i = 10;
  
  // To make the nested function have access to the
  // parent function's instance data, you can either
  // return it from the parent or declare it as an
  // instance method of the parent (shown here):
  this.b = function(){
    console.log("Regular function ", this.i, this);
  }
}
    
// Invoke a as a constructor function
let newA = new a();

// Now call b within the context of a
newA.b();

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

1 Comment

Thank you so much @Scott Marcus
0

You need to return the function first as shown below:

function a(){
    this.i = 10;
   return  function b(){
        console.log("Regular function ",this.i, this)
    }
}

And then call it using:

a()()

UPDATE: this keyword in the above example will point to the global scope. To make sure we use this within the function context we can use call() method on function a() and pass the object to which this will associate it's scope.

function a(){
    this.i = 10;
   return  b = ()=>{
        console.log("Regular function ",this.i,this)
    }
}

a.call({i:10})();

Note: I have also used arrow method for function b() to keep this scope used within it as its function a()'s scope.

6 Comments

a()() not a()b(). Also you need to remove the comma before return
TYpo ... My Bad.. Just edited. Thanks for highlighting mate. Edited properly Sir. Thank you very much :)
If you call the function this way, you will be creating an i property on the Global object.
You are right, this will point to the global scope. I can use arrow function to handle it also. Right? Or use call()
Arrow won't work.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.