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;
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
add a comment |
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
add a comment |
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
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
javascript
edited 38 mins ago
Dacre Denny
15.6k41333
15.6k41333
asked 1 hour ago
PeterPeter
511210
511210
add a comment |
add a comment |
2 Answers
2
active
oldest
votes
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]();
Very clear answer, thanks!
– Peter
49 mins ago
You're welcome - glad I could help :)
– Dacre Denny
39 mins ago
add a comment |
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
thisbinding 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]();add a comment |
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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]();
Very clear answer, thanks!
– Peter
49 mins ago
You're welcome - glad I could help :)
– Dacre Denny
39 mins ago
add a comment |
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]();
Very clear answer, thanks!
– Peter
49 mins ago
You're welcome - glad I could help :)
– Dacre Denny
39 mins ago
add a comment |
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]();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]();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
add a comment |
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
add a comment |
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
thisbinding 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]();add a comment |
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
thisbinding 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]();add a comment |
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
thisbinding 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]();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
thisbinding 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]();answered 43 mins ago
Todd ChaffeeTodd Chaffee
4,2792133
4,2792133
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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