call() a function within its own contextIs there an “exists” function for jQuery?var functionName = function() vs function functionName() Is JavaScript a pass-by-reference or pass-by-value language?JavaScript closure inside loops – simple practical exampleSet a default parameter value for a JavaScript functionWhat is the purpose of the var keyword and when should I use it (or omit it)?How to break/exit from a each() function in JQuery?What is the difference between call and apply?How do I return the response from an asynchronous call?Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference

Is every story set in the future "science fiction"?

Is there a need for better software for writers?

Watching the game, having a puzzle

Is a vertical stabiliser needed for straight line flight in a glider?

Why are parallelograms defined as quadrilaterals? What term would encompass polygons with greater than two parallel pairs?

Extending Kan fibrations, without using minimal fibrations

Thesis' "Future Work" section – is it acceptable to omit personal involvement in a mentioned project?

Is there any evidence to support the claim that the United States was "suckered into WW1" by Zionists, made by Benjamin Freedman in his 1961 speech

What do "KAL." and "A.S." stand for in this inscription?

How to handle DM constantly stealing everything from sleeping characters?

No such column 'DeveloperName' on entity 'RecordType' after Summer '19 release on sandbox

Remove color cast in darktable?

Would encrypting a database protect against a compromised admin account?

How do I compare the result of "1d20+x, with advantage" to "1d20+y, without advantage", assuming x < y?

Names of the Six Tastes

How to efficiently lower your karma

How to select certain lines (n, n+4, n+8, n+12...) from the file?

Was the Highlands Ranch shooting the 115th mass shooting in the US in 2019

Has there been evidence of any other gods?

Best species to breed to intelligence

What can cause an unfrozen indoor copper drain pipe to crack?

Passport stamps art, can it be done?

Improving Sati-Sampajañña (situative wisdom)

Why was wildfire not used during the Battle of Winterfell?



call() a function within its own context


Is there an “exists” function for jQuery?var functionName = function() vs function functionName() Is JavaScript a pass-by-reference or pass-by-value language?JavaScript closure inside loops – simple practical exampleSet a default parameter value for a JavaScript functionWhat is the purpose of the var keyword and when should I use it (or omit it)?How to break/exit from a each() function in JQuery?What is the difference between call and apply?How do I return the response from an asynchronous call?Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








19


















var f = function() 
this.x = 5;
(function()
this.x = 3;
)();
console.log(this.x);
;

f.call(f);

f();

f.call();





Running var f as f.call(f) outputs 5. When running it as f() or f.call() outputs 3.



What happens in each case? What does the inner function's this refer to?










share|improve this question



















  • 3





    Don't confuse the two this references. Instead try to see there are two different stack frames. Each frame has a this reference. That this is either the default or it's been set by call(). The inner function can not be set. It's always the default. I think the default for this is window, but that depends if there is a module loader or not. I should know but I can't remember.

    – cgTag
    May 6 at 15:24







  • 3





    If you want to add some other scopes/context, use the .bind(context) method.

    – Adrian Preuss
    May 6 at 15:28











  • This is why you always should use strict mode…

    – Bergi
    May 6 at 16:45







  • 1





    It's also why you should use lambdas instead of anonymous functions

    – BlueRaja - Danny Pflughoeft
    May 6 at 18:21

















19


















var f = function() 
this.x = 5;
(function()
this.x = 3;
)();
console.log(this.x);
;

f.call(f);

f();

f.call();





Running var f as f.call(f) outputs 5. When running it as f() or f.call() outputs 3.



What happens in each case? What does the inner function's this refer to?










share|improve this question



















  • 3





    Don't confuse the two this references. Instead try to see there are two different stack frames. Each frame has a this reference. That this is either the default or it's been set by call(). The inner function can not be set. It's always the default. I think the default for this is window, but that depends if there is a module loader or not. I should know but I can't remember.

    – cgTag
    May 6 at 15:24







  • 3





    If you want to add some other scopes/context, use the .bind(context) method.

    – Adrian Preuss
    May 6 at 15:28











  • This is why you always should use strict mode…

    – Bergi
    May 6 at 16:45







  • 1





    It's also why you should use lambdas instead of anonymous functions

    – BlueRaja - Danny Pflughoeft
    May 6 at 18:21













19












19








19


1









var f = function() 
this.x = 5;
(function()
this.x = 3;
)();
console.log(this.x);
;

f.call(f);

f();

f.call();





Running var f as f.call(f) outputs 5. When running it as f() or f.call() outputs 3.



What happens in each case? What does the inner function's this refer to?










share|improve this question



















var f = function() 
this.x = 5;
(function()
this.x = 3;
)();
console.log(this.x);
;

f.call(f);

f();

f.call();





Running var f as f.call(f) outputs 5. When running it as f() or f.call() outputs 3.



What happens in each case? What does the inner function's this refer to?






var f = function() 
this.x = 5;
(function()
this.x = 3;
)();
console.log(this.x);
;

f.call(f);

f();

f.call();





var f = function() 
this.x = 5;
(function()
this.x = 3;
)();
console.log(this.x);
;

f.call(f);

f();

f.call();






javascript this






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited May 6 at 15:14









Derek Pollard

4,45252741




4,45252741










asked May 6 at 15:11









El AnonimoEl Anonimo

355415




355415







  • 3





    Don't confuse the two this references. Instead try to see there are two different stack frames. Each frame has a this reference. That this is either the default or it's been set by call(). The inner function can not be set. It's always the default. I think the default for this is window, but that depends if there is a module loader or not. I should know but I can't remember.

    – cgTag
    May 6 at 15:24







  • 3





    If you want to add some other scopes/context, use the .bind(context) method.

    – Adrian Preuss
    May 6 at 15:28











  • This is why you always should use strict mode…

    – Bergi
    May 6 at 16:45







  • 1





    It's also why you should use lambdas instead of anonymous functions

    – BlueRaja - Danny Pflughoeft
    May 6 at 18:21












  • 3





    Don't confuse the two this references. Instead try to see there are two different stack frames. Each frame has a this reference. That this is either the default or it's been set by call(). The inner function can not be set. It's always the default. I think the default for this is window, but that depends if there is a module loader or not. I should know but I can't remember.

    – cgTag
    May 6 at 15:24







  • 3





    If you want to add some other scopes/context, use the .bind(context) method.

    – Adrian Preuss
    May 6 at 15:28











  • This is why you always should use strict mode…

    – Bergi
    May 6 at 16:45







  • 1





    It's also why you should use lambdas instead of anonymous functions

    – BlueRaja - Danny Pflughoeft
    May 6 at 18:21







3




3





Don't confuse the two this references. Instead try to see there are two different stack frames. Each frame has a this reference. That this is either the default or it's been set by call(). The inner function can not be set. It's always the default. I think the default for this is window, but that depends if there is a module loader or not. I should know but I can't remember.

– cgTag
May 6 at 15:24






Don't confuse the two this references. Instead try to see there are two different stack frames. Each frame has a this reference. That this is either the default or it's been set by call(). The inner function can not be set. It's always the default. I think the default for this is window, but that depends if there is a module loader or not. I should know but I can't remember.

– cgTag
May 6 at 15:24





3




3





If you want to add some other scopes/context, use the .bind(context) method.

– Adrian Preuss
May 6 at 15:28





If you want to add some other scopes/context, use the .bind(context) method.

– Adrian Preuss
May 6 at 15:28













This is why you always should use strict mode…

– Bergi
May 6 at 16:45






This is why you always should use strict mode…

– Bergi
May 6 at 16:45





1




1





It's also why you should use lambdas instead of anonymous functions

– BlueRaja - Danny Pflughoeft
May 6 at 18:21





It's also why you should use lambdas instead of anonymous functions

– BlueRaja - Danny Pflughoeft
May 6 at 18:21












4 Answers
4






active

oldest

votes


















14














First Case:



In the first you are calling the function. And inside the function the function itself i.e f is set as this. So in first example this.x = 5; sets the property x on the function.



When the inner function is called this refers to window object so this.x = 3; changes the x property of window object.



When it logs console.log(this.x); here the same property x which was set as property of function is logged.



Second Case:



In the second example this inside the outer function refers to window so when this.x = 3; is evaluated the window.x becomes 3. As this refers to window in outer function so console.log(this.x); logs window.x which is 3



Conclusion:



The conclusion of the whole discussion is that if no argument is passed to call() then automatically window object is binded. According to MDN




thisArg


Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.




See the below snippet.






function foo()
console.log(this);

foo.call(foo); //foo function
foo.call(); //window object








share|improve this answer
































    6














    If there is no specific context, this will be window. Your inner function always runs without a context, so it'll set window.x to 3. If you call f(), it will also run with this being window therefore logging the 3.



    If you however do f.call(f), this will be the f function object, and it's x property will be set to 5.



     f.call(f)
    console.log(
    f.x, // 5
    window.x // 3
    );


    I'd recommend stepping through it with the debugger if it isn't clear yet.






    share|improve this answer
































      2














      When you call f with a reference to itself, it sets the x property to 5 on the function and the inner anonymous function has its this referring to the window, so it sets window.x to 3. Outside the anonymous function, this still refers to the function f, so console.log(this.x) outputs 5.



      When you invoke f using f() or f.call() the function f and the anonymous function inside it have a this reference set to the window (the default) and so changing the value of this.x inside or outside the anonymous function affects the output result.



      You can see this clearly if you console.log the values of this inside the function f and inside the inner anonymous function.






      var f = function() 
      console.log("This inside function f:", this.toString());
      this.x = 5;
      (function()
      console.log("This inside anonymous inner function:", this.toString());
      this.x = 3;
      )();
      console.log(this.x);
      ;
      console.log("calling function x with this set to itself");
      f.call(f);
      console.log("---------------")
      console.log("invoking function x with brackets ()")
      f();
      console.log("---------------")
      console.log("calling function x without setting this context")
      f.call();
      console.log("---------------")








      share|improve this answer






























        1














        Further to the other answers, should you want predictable behaviour, you have at least 2 methods available to you.



        Method 1: (closure)



        var f = function() 
        this.x = 5;
        var that = this;
        (function()
        that.x = 3;
        )();
        console.log(this.x);
        ;

        f.call(f); // 3

        f(); // 3

        f.call(); // 3


        Method 2: (arrow function)



        var f = () => 
        this.x = 5;
        (function()
        this.x = 3;
        )();
        console.log(this.x);
        ;

        f.call(f); // 3

        f(); // 3

        f.call(); // 3





        share|improve this answer

























          Your Answer






          StackExchange.ifUsing("editor", function ()
          StackExchange.using("externalEditor", function ()
          StackExchange.using("snippets", function ()
          StackExchange.snippets.init();
          );
          );
          , "code-snippets");

          StackExchange.ready(function()
          var channelOptions =
          tags: "".split(" "),
          id: "1"
          ;
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function()
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled)
          StackExchange.using("snippets", function()
          createEditor();
          );

          else
          createEditor();

          );

          function createEditor()
          StackExchange.prepareEditor(
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader:
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          ,
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          );



          );













          draft saved

          draft discarded


















          StackExchange.ready(
          function ()
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56007944%2fcall-a-function-within-its-own-context%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          4 Answers
          4






          active

          oldest

          votes








          4 Answers
          4






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          14














          First Case:



          In the first you are calling the function. And inside the function the function itself i.e f is set as this. So in first example this.x = 5; sets the property x on the function.



          When the inner function is called this refers to window object so this.x = 3; changes the x property of window object.



          When it logs console.log(this.x); here the same property x which was set as property of function is logged.



          Second Case:



          In the second example this inside the outer function refers to window so when this.x = 3; is evaluated the window.x becomes 3. As this refers to window in outer function so console.log(this.x); logs window.x which is 3



          Conclusion:



          The conclusion of the whole discussion is that if no argument is passed to call() then automatically window object is binded. According to MDN




          thisArg


          Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.




          See the below snippet.






          function foo()
          console.log(this);

          foo.call(foo); //foo function
          foo.call(); //window object








          share|improve this answer





























            14














            First Case:



            In the first you are calling the function. And inside the function the function itself i.e f is set as this. So in first example this.x = 5; sets the property x on the function.



            When the inner function is called this refers to window object so this.x = 3; changes the x property of window object.



            When it logs console.log(this.x); here the same property x which was set as property of function is logged.



            Second Case:



            In the second example this inside the outer function refers to window so when this.x = 3; is evaluated the window.x becomes 3. As this refers to window in outer function so console.log(this.x); logs window.x which is 3



            Conclusion:



            The conclusion of the whole discussion is that if no argument is passed to call() then automatically window object is binded. According to MDN




            thisArg


            Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.




            See the below snippet.






            function foo()
            console.log(this);

            foo.call(foo); //foo function
            foo.call(); //window object








            share|improve this answer



























              14












              14








              14







              First Case:



              In the first you are calling the function. And inside the function the function itself i.e f is set as this. So in first example this.x = 5; sets the property x on the function.



              When the inner function is called this refers to window object so this.x = 3; changes the x property of window object.



              When it logs console.log(this.x); here the same property x which was set as property of function is logged.



              Second Case:



              In the second example this inside the outer function refers to window so when this.x = 3; is evaluated the window.x becomes 3. As this refers to window in outer function so console.log(this.x); logs window.x which is 3



              Conclusion:



              The conclusion of the whole discussion is that if no argument is passed to call() then automatically window object is binded. According to MDN




              thisArg


              Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.




              See the below snippet.






              function foo()
              console.log(this);

              foo.call(foo); //foo function
              foo.call(); //window object








              share|improve this answer















              First Case:



              In the first you are calling the function. And inside the function the function itself i.e f is set as this. So in first example this.x = 5; sets the property x on the function.



              When the inner function is called this refers to window object so this.x = 3; changes the x property of window object.



              When it logs console.log(this.x); here the same property x which was set as property of function is logged.



              Second Case:



              In the second example this inside the outer function refers to window so when this.x = 3; is evaluated the window.x becomes 3. As this refers to window in outer function so console.log(this.x); logs window.x which is 3



              Conclusion:



              The conclusion of the whole discussion is that if no argument is passed to call() then automatically window object is binded. According to MDN




              thisArg


              Optional. The value of this provided for the call to a function. Note that this may not be the actual value seen by the method: if the method is a function in non-strict mode, null and undefined will be replaced with the global object and primitive values will be converted to objects.




              See the below snippet.






              function foo()
              console.log(this);

              foo.call(foo); //foo function
              foo.call(); //window object








              function foo()
              console.log(this);

              foo.call(foo); //foo function
              foo.call(); //window object





              function foo()
              console.log(this);

              foo.call(foo); //foo function
              foo.call(); //window object






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited May 6 at 15:37

























              answered May 6 at 15:21









              Maheer AliMaheer Ali

              15.7k11632




              15.7k11632























                  6














                  If there is no specific context, this will be window. Your inner function always runs without a context, so it'll set window.x to 3. If you call f(), it will also run with this being window therefore logging the 3.



                  If you however do f.call(f), this will be the f function object, and it's x property will be set to 5.



                   f.call(f)
                  console.log(
                  f.x, // 5
                  window.x // 3
                  );


                  I'd recommend stepping through it with the debugger if it isn't clear yet.






                  share|improve this answer





























                    6














                    If there is no specific context, this will be window. Your inner function always runs without a context, so it'll set window.x to 3. If you call f(), it will also run with this being window therefore logging the 3.



                    If you however do f.call(f), this will be the f function object, and it's x property will be set to 5.



                     f.call(f)
                    console.log(
                    f.x, // 5
                    window.x // 3
                    );


                    I'd recommend stepping through it with the debugger if it isn't clear yet.






                    share|improve this answer



























                      6












                      6








                      6







                      If there is no specific context, this will be window. Your inner function always runs without a context, so it'll set window.x to 3. If you call f(), it will also run with this being window therefore logging the 3.



                      If you however do f.call(f), this will be the f function object, and it's x property will be set to 5.



                       f.call(f)
                      console.log(
                      f.x, // 5
                      window.x // 3
                      );


                      I'd recommend stepping through it with the debugger if it isn't clear yet.






                      share|improve this answer















                      If there is no specific context, this will be window. Your inner function always runs without a context, so it'll set window.x to 3. If you call f(), it will also run with this being window therefore logging the 3.



                      If you however do f.call(f), this will be the f function object, and it's x property will be set to 5.



                       f.call(f)
                      console.log(
                      f.x, // 5
                      window.x // 3
                      );


                      I'd recommend stepping through it with the debugger if it isn't clear yet.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      edited May 6 at 15:31

























                      answered May 6 at 15:23









                      Jonas WilmsJonas Wilms

                      69.6k63763




                      69.6k63763





















                          2














                          When you call f with a reference to itself, it sets the x property to 5 on the function and the inner anonymous function has its this referring to the window, so it sets window.x to 3. Outside the anonymous function, this still refers to the function f, so console.log(this.x) outputs 5.



                          When you invoke f using f() or f.call() the function f and the anonymous function inside it have a this reference set to the window (the default) and so changing the value of this.x inside or outside the anonymous function affects the output result.



                          You can see this clearly if you console.log the values of this inside the function f and inside the inner anonymous function.






                          var f = function() 
                          console.log("This inside function f:", this.toString());
                          this.x = 5;
                          (function()
                          console.log("This inside anonymous inner function:", this.toString());
                          this.x = 3;
                          )();
                          console.log(this.x);
                          ;
                          console.log("calling function x with this set to itself");
                          f.call(f);
                          console.log("---------------")
                          console.log("invoking function x with brackets ()")
                          f();
                          console.log("---------------")
                          console.log("calling function x without setting this context")
                          f.call();
                          console.log("---------------")








                          share|improve this answer



























                            2














                            When you call f with a reference to itself, it sets the x property to 5 on the function and the inner anonymous function has its this referring to the window, so it sets window.x to 3. Outside the anonymous function, this still refers to the function f, so console.log(this.x) outputs 5.



                            When you invoke f using f() or f.call() the function f and the anonymous function inside it have a this reference set to the window (the default) and so changing the value of this.x inside or outside the anonymous function affects the output result.



                            You can see this clearly if you console.log the values of this inside the function f and inside the inner anonymous function.






                            var f = function() 
                            console.log("This inside function f:", this.toString());
                            this.x = 5;
                            (function()
                            console.log("This inside anonymous inner function:", this.toString());
                            this.x = 3;
                            )();
                            console.log(this.x);
                            ;
                            console.log("calling function x with this set to itself");
                            f.call(f);
                            console.log("---------------")
                            console.log("invoking function x with brackets ()")
                            f();
                            console.log("---------------")
                            console.log("calling function x without setting this context")
                            f.call();
                            console.log("---------------")








                            share|improve this answer

























                              2












                              2








                              2







                              When you call f with a reference to itself, it sets the x property to 5 on the function and the inner anonymous function has its this referring to the window, so it sets window.x to 3. Outside the anonymous function, this still refers to the function f, so console.log(this.x) outputs 5.



                              When you invoke f using f() or f.call() the function f and the anonymous function inside it have a this reference set to the window (the default) and so changing the value of this.x inside or outside the anonymous function affects the output result.



                              You can see this clearly if you console.log the values of this inside the function f and inside the inner anonymous function.






                              var f = function() 
                              console.log("This inside function f:", this.toString());
                              this.x = 5;
                              (function()
                              console.log("This inside anonymous inner function:", this.toString());
                              this.x = 3;
                              )();
                              console.log(this.x);
                              ;
                              console.log("calling function x with this set to itself");
                              f.call(f);
                              console.log("---------------")
                              console.log("invoking function x with brackets ()")
                              f();
                              console.log("---------------")
                              console.log("calling function x without setting this context")
                              f.call();
                              console.log("---------------")








                              share|improve this answer













                              When you call f with a reference to itself, it sets the x property to 5 on the function and the inner anonymous function has its this referring to the window, so it sets window.x to 3. Outside the anonymous function, this still refers to the function f, so console.log(this.x) outputs 5.



                              When you invoke f using f() or f.call() the function f and the anonymous function inside it have a this reference set to the window (the default) and so changing the value of this.x inside or outside the anonymous function affects the output result.



                              You can see this clearly if you console.log the values of this inside the function f and inside the inner anonymous function.






                              var f = function() 
                              console.log("This inside function f:", this.toString());
                              this.x = 5;
                              (function()
                              console.log("This inside anonymous inner function:", this.toString());
                              this.x = 3;
                              )();
                              console.log(this.x);
                              ;
                              console.log("calling function x with this set to itself");
                              f.call(f);
                              console.log("---------------")
                              console.log("invoking function x with brackets ()")
                              f();
                              console.log("---------------")
                              console.log("calling function x without setting this context")
                              f.call();
                              console.log("---------------")








                              var f = function() 
                              console.log("This inside function f:", this.toString());
                              this.x = 5;
                              (function()
                              console.log("This inside anonymous inner function:", this.toString());
                              this.x = 3;
                              )();
                              console.log(this.x);
                              ;
                              console.log("calling function x with this set to itself");
                              f.call(f);
                              console.log("---------------")
                              console.log("invoking function x with brackets ()")
                              f();
                              console.log("---------------")
                              console.log("calling function x without setting this context")
                              f.call();
                              console.log("---------------")





                              var f = function() 
                              console.log("This inside function f:", this.toString());
                              this.x = 5;
                              (function()
                              console.log("This inside anonymous inner function:", this.toString());
                              this.x = 3;
                              )();
                              console.log(this.x);
                              ;
                              console.log("calling function x with this set to itself");
                              f.call(f);
                              console.log("---------------")
                              console.log("invoking function x with brackets ()")
                              f();
                              console.log("---------------")
                              console.log("calling function x without setting this context")
                              f.call();
                              console.log("---------------")






                              share|improve this answer












                              share|improve this answer



                              share|improve this answer










                              answered May 6 at 15:27









                              hev1hev1

                              6,0633729




                              6,0633729





















                                  1














                                  Further to the other answers, should you want predictable behaviour, you have at least 2 methods available to you.



                                  Method 1: (closure)



                                  var f = function() 
                                  this.x = 5;
                                  var that = this;
                                  (function()
                                  that.x = 3;
                                  )();
                                  console.log(this.x);
                                  ;

                                  f.call(f); // 3

                                  f(); // 3

                                  f.call(); // 3


                                  Method 2: (arrow function)



                                  var f = () => 
                                  this.x = 5;
                                  (function()
                                  this.x = 3;
                                  )();
                                  console.log(this.x);
                                  ;

                                  f.call(f); // 3

                                  f(); // 3

                                  f.call(); // 3





                                  share|improve this answer





























                                    1














                                    Further to the other answers, should you want predictable behaviour, you have at least 2 methods available to you.



                                    Method 1: (closure)



                                    var f = function() 
                                    this.x = 5;
                                    var that = this;
                                    (function()
                                    that.x = 3;
                                    )();
                                    console.log(this.x);
                                    ;

                                    f.call(f); // 3

                                    f(); // 3

                                    f.call(); // 3


                                    Method 2: (arrow function)



                                    var f = () => 
                                    this.x = 5;
                                    (function()
                                    this.x = 3;
                                    )();
                                    console.log(this.x);
                                    ;

                                    f.call(f); // 3

                                    f(); // 3

                                    f.call(); // 3





                                    share|improve this answer



























                                      1












                                      1








                                      1







                                      Further to the other answers, should you want predictable behaviour, you have at least 2 methods available to you.



                                      Method 1: (closure)



                                      var f = function() 
                                      this.x = 5;
                                      var that = this;
                                      (function()
                                      that.x = 3;
                                      )();
                                      console.log(this.x);
                                      ;

                                      f.call(f); // 3

                                      f(); // 3

                                      f.call(); // 3


                                      Method 2: (arrow function)



                                      var f = () => 
                                      this.x = 5;
                                      (function()
                                      this.x = 3;
                                      )();
                                      console.log(this.x);
                                      ;

                                      f.call(f); // 3

                                      f(); // 3

                                      f.call(); // 3





                                      share|improve this answer















                                      Further to the other answers, should you want predictable behaviour, you have at least 2 methods available to you.



                                      Method 1: (closure)



                                      var f = function() 
                                      this.x = 5;
                                      var that = this;
                                      (function()
                                      that.x = 3;
                                      )();
                                      console.log(this.x);
                                      ;

                                      f.call(f); // 3

                                      f(); // 3

                                      f.call(); // 3


                                      Method 2: (arrow function)



                                      var f = () => 
                                      this.x = 5;
                                      (function()
                                      this.x = 3;
                                      )();
                                      console.log(this.x);
                                      ;

                                      f.call(f); // 3

                                      f(); // 3

                                      f.call(); // 3






                                      share|improve this answer














                                      share|improve this answer



                                      share|improve this answer








                                      edited 2 days ago

























                                      answered 2 days ago









                                      Adrian BartholomewAdrian Bartholomew

                                      70941125




                                      70941125



























                                          draft saved

                                          draft discarded
















































                                          Thanks for contributing an answer to Stack Overflow!


                                          • Please be sure to answer the question. Provide details and share your research!

                                          But avoid


                                          • Asking for help, clarification, or responding to other answers.

                                          • Making statements based on opinion; back them up with references or personal experience.

                                          To learn more, see our tips on writing great answers.




                                          draft saved


                                          draft discarded














                                          StackExchange.ready(
                                          function ()
                                          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f56007944%2fcall-a-function-within-its-own-context%23new-answer', 'question_page');

                                          );

                                          Post as a guest















                                          Required, but never shown





















































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown

































                                          Required, but never shown














                                          Required, but never shown












                                          Required, but never shown







                                          Required, but never shown







                                          Popular posts from this blog

                                          Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

                                          Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

                                          Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?