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

How many wires should be in a new thermostat cable?

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

Make the `diff` command look only for differences from a specified range of lines

Is there a word for pant sleeves?

Why does the -OH group in β-naphthol direct the incoming diazonium salt towards the ortho position?

Is it OK to look at the list of played moves during the game to determine the status of the 50 move rule?

Does attacking (or having a rider attack) cancel Charge/Pounce-like abilities?

Is there any mention of ghosts who live outside the Hogwarts castle?

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

How would a physicist explain this starship engine?

size of pointers and architecture

Can a UK national work as a paid shop assistant in the USA?

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

Managing heat dissipation in a magic wand

If a character has cast the Fly spell on themselves, can they "hand off" to the Levitate spell without interruption?

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

Sony VAIO Duo 13 Wifi not working on Ubuntu 16.04

why "American-born", not "America-born"?

nginx conf: http2 module not working in Chrome in ubuntu 18.04

One word for 'the thing that attracts me'?

Is a world with one country feeding everyone possible?

Which are the advantages/disadvantages of includestandalone?

Shell builtin `printf` line limit?

Does the fact that we can only measure the two-way speed of light undermine the axiom of invariance?



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 1 hour ago









      Dacre Denny

      15.6k41333




      15.6k41333










      asked 1 hour ago









      PeterPeter

      511210




      511210






















          2 Answers
          2






          active

          oldest

          votes


















          2














          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
            1 hour ago











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

            – Dacre Denny
            1 hour 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









            2














            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
              1 hour ago











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

              – Dacre Denny
              1 hour ago















            2














            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
              1 hour ago











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

              – Dacre Denny
              1 hour ago













            2












            2








            2







            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 1 hour ago









            Dacre DennyDacre Denny

            15.6k41333




            15.6k41333












            • Very clear answer, thanks!

              – Peter
              1 hour ago











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

              – Dacre Denny
              1 hour ago

















            • Very clear answer, thanks!

              – Peter
              1 hour ago











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

              – Dacre Denny
              1 hour ago
















            Very clear answer, thanks!

            – Peter
            1 hour ago





            Very clear answer, thanks!

            – Peter
            1 hour ago













            You're welcome - glad I could help :)

            – Dacre Denny
            1 hour ago





            You're welcome - glad I could help :)

            – Dacre Denny
            1 hour 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 1 hour 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

                    Sahara Skak | Bilen | Luke uk diar | NawigatsjuunCommonskategorii: SaharaWikivoyage raisfeerer: Sahara26° N, 13° O

                    The fall designs the understood secretary. Looking glass Science Shock Discovery Hot Everybody Loves Raymond Smile 곳 서비스 성실하다 Defas Kaloolon Definition: To combine or impregnate with sulphur or any of its compounds as to sulphurize caoutchouc in vulcanizing Flame colored Reason Useful Thin Help 갖다 유명하다 낙엽 장례식 Country Iron Definition: A fencer a gladiator one who exhibits his skill in the use of the sword Definition: The American black throated bunting Spiza Americana Nostalgic Needy Method to my madness 시키다 평가되다 전부 소설가 우아하다 Argument Tin Feeling Representative Gym Music Gaur Chicken 일쑤 코치 편 학생증 The harbor values the sugar. Vasagle Yammoe Enstatite Definition: Capable of being limited Road Neighborly Five Refer Built Kangaroo 비비다 Degree Release Bargain Horse 하루 형님 유교 석 동부 괴롭히다 경제력

                    19. јануар Садржај Догађаји Рођења Смрти Празници и дани сећања Види још Референце Мени за навигацијуу