JavaScript: Access 'this' when calling function stored in variableStop setInterval call in JavaScriptWhen to use double or single quotes in JavaScript?What is the scope of variables in JavaScript?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionCheck if a variable is a string in JavaScriptJavaScript check if variable exists (is defined/initialized)Is there a standard function to check for null, undefined, or blank variables in JavaScript?indexOf method in an object array?Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it

Real Analysis: Proof of the equivalent definitions of the derivative.

What technology is there beyond RAID for disk cluster in a server

VHDL: Why is it hard to desgin a floating point unit in hardware?

Why did Nick Fury not hesitate in blowing up the plane he thought was carrying a nuke?

Way of refund if scammed?

Was murdering a slave illegal in American slavery, and if so, what punishments were given for it?

What is the required burn to keep a satellite at a Lagrangian point?

Shell builtin `printf` line limit?

Coloring lines in a graph the same color if they are the same length

Island Perimeter

Is being an extrovert a necessary condition to be a manager?

Johnson-Nyquist noise for a lossy inductor?

size of pointers and architecture

How many wires should be in a new thermostat cable?

Is a world with one country feeding everyone possible?

Singular Integration

If change in free energy (G) is positive, how do those reactions still occur?

What does it mean for something to be strictly less than epsilon for an arbitrary epsilon?

Managing heat dissipation in a magic wand

Department head said that group project may be rejected. How to mitigate?

Which values for voltage divider

Illustrating that universal optimality is stronger than sphere packing

Adobe Illustrator: How can I change the profile of a dashed stroke?

Find this Unique UVC Palindrome ( ignoring signs and decimal) from Given Fractional Relationship



JavaScript: Access 'this' when calling function stored in variable


Stop setInterval call in JavaScriptWhen to use double or single quotes in JavaScript?What is the scope of variables in JavaScript?How do you check if a variable is an array in JavaScript?Set a default parameter value for a JavaScript functionCheck if a variable is a string in JavaScriptJavaScript check if variable exists (is defined/initialized)Is there a standard function to check for null, undefined, or blank variables in JavaScript?indexOf method in an object array?Pure JavaScript equivalent of jQuery's $.ready() - how to call a function when the page/DOM is ready for it






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








7















I'm new to JavaScript so this is possibly a trivial question:



I'm trying to construct an object that stores a mapping from a set of integers to some of its methods, i.e. something like this:



'use strict';

function Foo()
this.funcs =
1: this.func1,
2: this.func2,



Foo.prototype.func1 = function()
this.prop = 1;


Foo.prototype.func2 = function()
this.prop = 2;



I'd then like to be able to call methods of Foo like this:



foo = new Foo();
var func = foo.funcs[1];
func();


But this results in: Cannot set property 'prop' of undefined, i.e. this does not refer to foo.



What's the problem here and is there a better way to implement this?










share|improve this question






























    7















    I'm new to JavaScript so this is possibly a trivial question:



    I'm trying to construct an object that stores a mapping from a set of integers to some of its methods, i.e. something like this:



    'use strict';

    function Foo()
    this.funcs =
    1: this.func1,
    2: this.func2,



    Foo.prototype.func1 = function()
    this.prop = 1;


    Foo.prototype.func2 = function()
    this.prop = 2;



    I'd then like to be able to call methods of Foo like this:



    foo = new Foo();
    var func = foo.funcs[1];
    func();


    But this results in: Cannot set property 'prop' of undefined, i.e. this does not refer to foo.



    What's the problem here and is there a better way to implement this?










    share|improve this question


























      7












      7








      7








      I'm new to JavaScript so this is possibly a trivial question:



      I'm trying to construct an object that stores a mapping from a set of integers to some of its methods, i.e. something like this:



      'use strict';

      function Foo()
      this.funcs =
      1: this.func1,
      2: this.func2,



      Foo.prototype.func1 = function()
      this.prop = 1;


      Foo.prototype.func2 = function()
      this.prop = 2;



      I'd then like to be able to call methods of Foo like this:



      foo = new Foo();
      var func = foo.funcs[1];
      func();


      But this results in: Cannot set property 'prop' of undefined, i.e. this does not refer to foo.



      What's the problem here and is there a better way to implement this?










      share|improve this question
















      I'm new to JavaScript so this is possibly a trivial question:



      I'm trying to construct an object that stores a mapping from a set of integers to some of its methods, i.e. something like this:



      'use strict';

      function Foo()
      this.funcs =
      1: this.func1,
      2: this.func2,



      Foo.prototype.func1 = function()
      this.prop = 1;


      Foo.prototype.func2 = function()
      this.prop = 2;



      I'd then like to be able to call methods of Foo like this:



      foo = new Foo();
      var func = foo.funcs[1];
      func();


      But this results in: Cannot set property 'prop' of undefined, i.e. this does not refer to foo.



      What's the problem here and is there a better way to implement this?







      javascript






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 38 mins ago









      Dacre Denny

      15.6k41333




      15.6k41333










      asked 1 hour ago









      PeterPeter

      511210




      511210






















          2 Answers
          2






          active

          oldest

          votes


















          3














          There are a few ways to achieve this however the better approach would be to bind() each function to the instance of Foo() that is being instantiated by passing this to bind() of each function:



          this.func1.bind(this)


          That will ensure that this, for func1 and func2 is defined as the instance of Foo(), which will ensure that this.prop can be accessed and assigned as expected:






          'use strict';

          function Foo()
          this.funcs =
          /* Bind the functions to this Foo() instance */
          1: this.func1.bind(this),
          2: this.func2.bind(this),



          Foo.prototype.func1 = function()
          this.prop = 1;
          console.log('called func1. this.prop =', this.prop);


          Foo.prototype.func2 = function()
          this.prop = 2;
          console.log('called func2. this.prop =', this.prop);



          const foo = new Foo();
          var func = foo.funcs[1];
          func();

          foo.funcs[2]();








          share|improve this answer























          • Very clear answer, thanks!

            – Peter
            49 mins ago











          • You're welcome - glad I could help :)

            – Dacre Denny
            39 mins ago


















          2














          Your problem is this line:



          var func = foo.funcs[1];


          JavaScript determines the value of this based on how a function is called. If you use dot notation, such as foo.funcs[1](); then the value of this will associated with the foo object. But when you run func(), that's just a plain function and this will have the default value of undefined.



          It would be worth your time to read the two chapters of You Don't Know JS that discuss this. It should take less than an hour to learn, and you'll be way ahead of most JS programmers once you learn it.



          The rules might not make sense until you read the chapter, but they are summarized below:




          Determining the this binding for an executing function requires
          finding the direct call-site of that function. Once examined, four
          rules can be applied to the call-site, in this order of precedence:



          Called with new? Use the newly constructed object.



          Called with call or apply (or bind)? Use the specified object.



          Called with a context object owning the call? Use that context object.



          Default: undefined in strict mode, global object otherwise.




          Based on the above rules, the code below is the simplest way you could get it to work the way you are expecting it to:






          'use strict';

          function Foo()
          this.funcs =
          1: this.func1,
          2: this.func2,



          Foo.prototype.func1 = function()
          this.prop = 1;
          console.log('called func1. this.prop =', this.prop);


          Foo.prototype.func2 = function()
          this.prop = 2;
          console.log('called func2. this.prop =', this.prop);



          const foo = new Foo();
          foo.funcs[1]();








          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%2f56212424%2fjavascript-access-this-when-calling-function-stored-in-variable%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            3














            There are a few ways to achieve this however the better approach would be to bind() each function to the instance of Foo() that is being instantiated by passing this to bind() of each function:



            this.func1.bind(this)


            That will ensure that this, for func1 and func2 is defined as the instance of Foo(), which will ensure that this.prop can be accessed and assigned as expected:






            'use strict';

            function Foo()
            this.funcs =
            /* Bind the functions to this Foo() instance */
            1: this.func1.bind(this),
            2: this.func2.bind(this),



            Foo.prototype.func1 = function()
            this.prop = 1;
            console.log('called func1. this.prop =', this.prop);


            Foo.prototype.func2 = function()
            this.prop = 2;
            console.log('called func2. this.prop =', this.prop);



            const foo = new Foo();
            var func = foo.funcs[1];
            func();

            foo.funcs[2]();








            share|improve this answer























            • Very clear answer, thanks!

              – Peter
              49 mins ago











            • You're welcome - glad I could help :)

              – Dacre Denny
              39 mins ago















            3














            There are a few ways to achieve this however the better approach would be to bind() each function to the instance of Foo() that is being instantiated by passing this to bind() of each function:



            this.func1.bind(this)


            That will ensure that this, for func1 and func2 is defined as the instance of Foo(), which will ensure that this.prop can be accessed and assigned as expected:






            'use strict';

            function Foo()
            this.funcs =
            /* Bind the functions to this Foo() instance */
            1: this.func1.bind(this),
            2: this.func2.bind(this),



            Foo.prototype.func1 = function()
            this.prop = 1;
            console.log('called func1. this.prop =', this.prop);


            Foo.prototype.func2 = function()
            this.prop = 2;
            console.log('called func2. this.prop =', this.prop);



            const foo = new Foo();
            var func = foo.funcs[1];
            func();

            foo.funcs[2]();








            share|improve this answer























            • Very clear answer, thanks!

              – Peter
              49 mins ago











            • You're welcome - glad I could help :)

              – Dacre Denny
              39 mins ago













            3












            3








            3







            There are a few ways to achieve this however the better approach would be to bind() each function to the instance of Foo() that is being instantiated by passing this to bind() of each function:



            this.func1.bind(this)


            That will ensure that this, for func1 and func2 is defined as the instance of Foo(), which will ensure that this.prop can be accessed and assigned as expected:






            'use strict';

            function Foo()
            this.funcs =
            /* Bind the functions to this Foo() instance */
            1: this.func1.bind(this),
            2: this.func2.bind(this),



            Foo.prototype.func1 = function()
            this.prop = 1;
            console.log('called func1. this.prop =', this.prop);


            Foo.prototype.func2 = function()
            this.prop = 2;
            console.log('called func2. this.prop =', this.prop);



            const foo = new Foo();
            var func = foo.funcs[1];
            func();

            foo.funcs[2]();








            share|improve this answer













            There are a few ways to achieve this however the better approach would be to bind() each function to the instance of Foo() that is being instantiated by passing this to bind() of each function:



            this.func1.bind(this)


            That will ensure that this, for func1 and func2 is defined as the instance of Foo(), which will ensure that this.prop can be accessed and assigned as expected:






            'use strict';

            function Foo()
            this.funcs =
            /* Bind the functions to this Foo() instance */
            1: this.func1.bind(this),
            2: this.func2.bind(this),



            Foo.prototype.func1 = function()
            this.prop = 1;
            console.log('called func1. this.prop =', this.prop);


            Foo.prototype.func2 = function()
            this.prop = 2;
            console.log('called func2. this.prop =', this.prop);



            const foo = new Foo();
            var func = foo.funcs[1];
            func();

            foo.funcs[2]();








            'use strict';

            function Foo()
            this.funcs =
            /* Bind the functions to this Foo() instance */
            1: this.func1.bind(this),
            2: this.func2.bind(this),



            Foo.prototype.func1 = function()
            this.prop = 1;
            console.log('called func1. this.prop =', this.prop);


            Foo.prototype.func2 = function()
            this.prop = 2;
            console.log('called func2. this.prop =', this.prop);



            const foo = new Foo();
            var func = foo.funcs[1];
            func();

            foo.funcs[2]();





            'use strict';

            function Foo()
            this.funcs =
            /* Bind the functions to this Foo() instance */
            1: this.func1.bind(this),
            2: this.func2.bind(this),



            Foo.prototype.func1 = function()
            this.prop = 1;
            console.log('called func1. this.prop =', this.prop);


            Foo.prototype.func2 = function()
            this.prop = 2;
            console.log('called func2. this.prop =', this.prop);



            const foo = new Foo();
            var func = foo.funcs[1];
            func();

            foo.funcs[2]();






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered 54 mins ago









            Dacre DennyDacre Denny

            15.6k41333




            15.6k41333












            • Very clear answer, thanks!

              – Peter
              49 mins ago











            • You're welcome - glad I could help :)

              – Dacre Denny
              39 mins ago

















            • Very clear answer, thanks!

              – Peter
              49 mins ago











            • You're welcome - glad I could help :)

              – Dacre Denny
              39 mins ago
















            Very clear answer, thanks!

            – Peter
            49 mins ago





            Very clear answer, thanks!

            – Peter
            49 mins ago













            You're welcome - glad I could help :)

            – Dacre Denny
            39 mins ago





            You're welcome - glad I could help :)

            – Dacre Denny
            39 mins ago













            2














            Your problem is this line:



            var func = foo.funcs[1];


            JavaScript determines the value of this based on how a function is called. If you use dot notation, such as foo.funcs[1](); then the value of this will associated with the foo object. But when you run func(), that's just a plain function and this will have the default value of undefined.



            It would be worth your time to read the two chapters of You Don't Know JS that discuss this. It should take less than an hour to learn, and you'll be way ahead of most JS programmers once you learn it.



            The rules might not make sense until you read the chapter, but they are summarized below:




            Determining the this binding for an executing function requires
            finding the direct call-site of that function. Once examined, four
            rules can be applied to the call-site, in this order of precedence:



            Called with new? Use the newly constructed object.



            Called with call or apply (or bind)? Use the specified object.



            Called with a context object owning the call? Use that context object.



            Default: undefined in strict mode, global object otherwise.




            Based on the above rules, the code below is the simplest way you could get it to work the way you are expecting it to:






            'use strict';

            function Foo()
            this.funcs =
            1: this.func1,
            2: this.func2,



            Foo.prototype.func1 = function()
            this.prop = 1;
            console.log('called func1. this.prop =', this.prop);


            Foo.prototype.func2 = function()
            this.prop = 2;
            console.log('called func2. this.prop =', this.prop);



            const foo = new Foo();
            foo.funcs[1]();








            share|improve this answer



























              2














              Your problem is this line:



              var func = foo.funcs[1];


              JavaScript determines the value of this based on how a function is called. If you use dot notation, such as foo.funcs[1](); then the value of this will associated with the foo object. But when you run func(), that's just a plain function and this will have the default value of undefined.



              It would be worth your time to read the two chapters of You Don't Know JS that discuss this. It should take less than an hour to learn, and you'll be way ahead of most JS programmers once you learn it.



              The rules might not make sense until you read the chapter, but they are summarized below:




              Determining the this binding for an executing function requires
              finding the direct call-site of that function. Once examined, four
              rules can be applied to the call-site, in this order of precedence:



              Called with new? Use the newly constructed object.



              Called with call or apply (or bind)? Use the specified object.



              Called with a context object owning the call? Use that context object.



              Default: undefined in strict mode, global object otherwise.




              Based on the above rules, the code below is the simplest way you could get it to work the way you are expecting it to:






              'use strict';

              function Foo()
              this.funcs =
              1: this.func1,
              2: this.func2,



              Foo.prototype.func1 = function()
              this.prop = 1;
              console.log('called func1. this.prop =', this.prop);


              Foo.prototype.func2 = function()
              this.prop = 2;
              console.log('called func2. this.prop =', this.prop);



              const foo = new Foo();
              foo.funcs[1]();








              share|improve this answer

























                2












                2








                2







                Your problem is this line:



                var func = foo.funcs[1];


                JavaScript determines the value of this based on how a function is called. If you use dot notation, such as foo.funcs[1](); then the value of this will associated with the foo object. But when you run func(), that's just a plain function and this will have the default value of undefined.



                It would be worth your time to read the two chapters of You Don't Know JS that discuss this. It should take less than an hour to learn, and you'll be way ahead of most JS programmers once you learn it.



                The rules might not make sense until you read the chapter, but they are summarized below:




                Determining the this binding for an executing function requires
                finding the direct call-site of that function. Once examined, four
                rules can be applied to the call-site, in this order of precedence:



                Called with new? Use the newly constructed object.



                Called with call or apply (or bind)? Use the specified object.



                Called with a context object owning the call? Use that context object.



                Default: undefined in strict mode, global object otherwise.




                Based on the above rules, the code below is the simplest way you could get it to work the way you are expecting it to:






                'use strict';

                function Foo()
                this.funcs =
                1: this.func1,
                2: this.func2,



                Foo.prototype.func1 = function()
                this.prop = 1;
                console.log('called func1. this.prop =', this.prop);


                Foo.prototype.func2 = function()
                this.prop = 2;
                console.log('called func2. this.prop =', this.prop);



                const foo = new Foo();
                foo.funcs[1]();








                share|improve this answer













                Your problem is this line:



                var func = foo.funcs[1];


                JavaScript determines the value of this based on how a function is called. If you use dot notation, such as foo.funcs[1](); then the value of this will associated with the foo object. But when you run func(), that's just a plain function and this will have the default value of undefined.



                It would be worth your time to read the two chapters of You Don't Know JS that discuss this. It should take less than an hour to learn, and you'll be way ahead of most JS programmers once you learn it.



                The rules might not make sense until you read the chapter, but they are summarized below:




                Determining the this binding for an executing function requires
                finding the direct call-site of that function. Once examined, four
                rules can be applied to the call-site, in this order of precedence:



                Called with new? Use the newly constructed object.



                Called with call or apply (or bind)? Use the specified object.



                Called with a context object owning the call? Use that context object.



                Default: undefined in strict mode, global object otherwise.




                Based on the above rules, the code below is the simplest way you could get it to work the way you are expecting it to:






                'use strict';

                function Foo()
                this.funcs =
                1: this.func1,
                2: this.func2,



                Foo.prototype.func1 = function()
                this.prop = 1;
                console.log('called func1. this.prop =', this.prop);


                Foo.prototype.func2 = function()
                this.prop = 2;
                console.log('called func2. this.prop =', this.prop);



                const foo = new Foo();
                foo.funcs[1]();








                'use strict';

                function Foo()
                this.funcs =
                1: this.func1,
                2: this.func2,



                Foo.prototype.func1 = function()
                this.prop = 1;
                console.log('called func1. this.prop =', this.prop);


                Foo.prototype.func2 = function()
                this.prop = 2;
                console.log('called func2. this.prop =', this.prop);



                const foo = new Foo();
                foo.funcs[1]();





                'use strict';

                function Foo()
                this.funcs =
                1: this.func1,
                2: this.func2,



                Foo.prototype.func1 = function()
                this.prop = 1;
                console.log('called func1. this.prop =', this.prop);


                Foo.prototype.func2 = function()
                this.prop = 2;
                console.log('called func2. this.prop =', this.prop);



                const foo = new Foo();
                foo.funcs[1]();






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered 43 mins ago









                Todd ChaffeeTodd Chaffee

                4,2792133




                4,2792133



























                    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%2f56212424%2fjavascript-access-this-when-calling-function-stored-in-variable%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

                    Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

                    Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

                    François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480