function a(){
this.i = 10,
function b(){
console.log("Regular function ",this.i, this)
}
}
Here I want to call function b
function a(){
this.i = 10,
function b(){
console.log("Regular function ",this.i, this)
}
}
Here I want to call function b
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();
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.
a()() not a()b(). Also you need to remove the comma before returni property on the Global object.