Home > OS >  How to call a specific function from inside a subfunction in javascript?
How to call a specific function from inside a subfunction in javascript?

Time:11-08

How do I call function "a" from "a.v" without a direct reference "a()"

function a(){
    alert("1");
    this.v=function(){alert("hi")};
}

CodePudding user response:

One way I can think of doing this without repeating a:

function a(){
    let indirect = arguments.callee;
    alert("1");
    indirect.v=function(){ indirect(); };
}

a();
a.v();

But this does not work under strict mode and you must call a before calling a.v.

You could also do:

function a(){
   alert('1');
   this.v = () => this();
}

a.v = a;
a.v();

This way you don't call a() and it also works under strict mode.

CodePudding user response:

Set its v property outside the function itself:

function a() {
  alert("1");

}

a.v = function() {
  a()
  alert("hi")
};

a.v()
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related