JavaScript Does given String exists as variable and function
I have a variable with has a member variable which is a function
let test = {
setup: function() { ...}
}
From some other source, I get the String "test.setup"
How can i check if
a.) variable test exists
b.) variable test has a child called setup
c.) the child setup is a function ?
d.) call the function
I already tested
let variableName = "test.setup";
window[variableName]
// undefined
{}.toString.call(variableName ) === '[object Function]'
// VM2052:1 Uncaught SyntaxError: Unexpected token .
window.hasOwnProperty("test")
// false
It would be nice, if you could solve my problem. It would be enough for me to see if there is a such a function and call it if its there. Otherwise Inform the user that there is no such a function.
Thank you very much in advance
javascript
add a comment |
I have a variable with has a member variable which is a function
let test = {
setup: function() { ...}
}
From some other source, I get the String "test.setup"
How can i check if
a.) variable test exists
b.) variable test has a child called setup
c.) the child setup is a function ?
d.) call the function
I already tested
let variableName = "test.setup";
window[variableName]
// undefined
{}.toString.call(variableName ) === '[object Function]'
// VM2052:1 Uncaught SyntaxError: Unexpected token .
window.hasOwnProperty("test")
// false
It would be nice, if you could solve my problem. It would be enough for me to see if there is a such a function and call it if its there. Otherwise Inform the user that there is no such a function.
Thank you very much in advance
javascript
2
Needing to dynamically know the names of variables is often an xy problem and has a pretty strong code smell that leads to needing things likeeval(). If you need to dynamically access something with a string key, that something should be part of a larger data structure, then the problem goes away.
– Mark Meyer
Jan 2 at 18:02
1
@MarkMeyer I agree. It's a symptom of a problem.
– cgTag
Jan 2 at 18:08
@MarkMeyer sometimes as developer you do not have the possibilities to change the bigger data structure and have to work with, what was given to you =(
– MasterOfDesaster
Jan 2 at 18:12
1
letandconsthave block scope, but if you declare the variable withvar, it'll have either global or local function scope (depending if it's declared inside a function or not). So if you declare it withvaroutside any functions, you can usewindow["variableNameHere"]to check if it exists. However, I do agree with the above: you should be defining it as an enclosed object and checking if the "variable name" exists as a key. If you can't access the original variable, at least you can copy it to one you can change.
– IceMetalPunk
Jan 2 at 18:20
add a comment |
I have a variable with has a member variable which is a function
let test = {
setup: function() { ...}
}
From some other source, I get the String "test.setup"
How can i check if
a.) variable test exists
b.) variable test has a child called setup
c.) the child setup is a function ?
d.) call the function
I already tested
let variableName = "test.setup";
window[variableName]
// undefined
{}.toString.call(variableName ) === '[object Function]'
// VM2052:1 Uncaught SyntaxError: Unexpected token .
window.hasOwnProperty("test")
// false
It would be nice, if you could solve my problem. It would be enough for me to see if there is a such a function and call it if its there. Otherwise Inform the user that there is no such a function.
Thank you very much in advance
javascript
I have a variable with has a member variable which is a function
let test = {
setup: function() { ...}
}
From some other source, I get the String "test.setup"
How can i check if
a.) variable test exists
b.) variable test has a child called setup
c.) the child setup is a function ?
d.) call the function
I already tested
let variableName = "test.setup";
window[variableName]
// undefined
{}.toString.call(variableName ) === '[object Function]'
// VM2052:1 Uncaught SyntaxError: Unexpected token .
window.hasOwnProperty("test")
// false
It would be nice, if you could solve my problem. It would be enough for me to see if there is a such a function and call it if its there. Otherwise Inform the user that there is no such a function.
Thank you very much in advance
javascript
javascript
asked Jan 2 at 17:58
MasterOfDesasterMasterOfDesaster
1136
1136
2
Needing to dynamically know the names of variables is often an xy problem and has a pretty strong code smell that leads to needing things likeeval(). If you need to dynamically access something with a string key, that something should be part of a larger data structure, then the problem goes away.
– Mark Meyer
Jan 2 at 18:02
1
@MarkMeyer I agree. It's a symptom of a problem.
– cgTag
Jan 2 at 18:08
@MarkMeyer sometimes as developer you do not have the possibilities to change the bigger data structure and have to work with, what was given to you =(
– MasterOfDesaster
Jan 2 at 18:12
1
letandconsthave block scope, but if you declare the variable withvar, it'll have either global or local function scope (depending if it's declared inside a function or not). So if you declare it withvaroutside any functions, you can usewindow["variableNameHere"]to check if it exists. However, I do agree with the above: you should be defining it as an enclosed object and checking if the "variable name" exists as a key. If you can't access the original variable, at least you can copy it to one you can change.
– IceMetalPunk
Jan 2 at 18:20
add a comment |
2
Needing to dynamically know the names of variables is often an xy problem and has a pretty strong code smell that leads to needing things likeeval(). If you need to dynamically access something with a string key, that something should be part of a larger data structure, then the problem goes away.
– Mark Meyer
Jan 2 at 18:02
1
@MarkMeyer I agree. It's a symptom of a problem.
– cgTag
Jan 2 at 18:08
@MarkMeyer sometimes as developer you do not have the possibilities to change the bigger data structure and have to work with, what was given to you =(
– MasterOfDesaster
Jan 2 at 18:12
1
letandconsthave block scope, but if you declare the variable withvar, it'll have either global or local function scope (depending if it's declared inside a function or not). So if you declare it withvaroutside any functions, you can usewindow["variableNameHere"]to check if it exists. However, I do agree with the above: you should be defining it as an enclosed object and checking if the "variable name" exists as a key. If you can't access the original variable, at least you can copy it to one you can change.
– IceMetalPunk
Jan 2 at 18:20
2
2
Needing to dynamically know the names of variables is often an xy problem and has a pretty strong code smell that leads to needing things like
eval(). If you need to dynamically access something with a string key, that something should be part of a larger data structure, then the problem goes away.– Mark Meyer
Jan 2 at 18:02
Needing to dynamically know the names of variables is often an xy problem and has a pretty strong code smell that leads to needing things like
eval(). If you need to dynamically access something with a string key, that something should be part of a larger data structure, then the problem goes away.– Mark Meyer
Jan 2 at 18:02
1
1
@MarkMeyer I agree. It's a symptom of a problem.
– cgTag
Jan 2 at 18:08
@MarkMeyer I agree. It's a symptom of a problem.
– cgTag
Jan 2 at 18:08
@MarkMeyer sometimes as developer you do not have the possibilities to change the bigger data structure and have to work with, what was given to you =(
– MasterOfDesaster
Jan 2 at 18:12
@MarkMeyer sometimes as developer you do not have the possibilities to change the bigger data structure and have to work with, what was given to you =(
– MasterOfDesaster
Jan 2 at 18:12
1
1
let and const have block scope, but if you declare the variable with var, it'll have either global or local function scope (depending if it's declared inside a function or not). So if you declare it with var outside any functions, you can use window["variableNameHere"] to check if it exists. However, I do agree with the above: you should be defining it as an enclosed object and checking if the "variable name" exists as a key. If you can't access the original variable, at least you can copy it to one you can change.– IceMetalPunk
Jan 2 at 18:20
let and const have block scope, but if you declare the variable with var, it'll have either global or local function scope (depending if it's declared inside a function or not). So if you declare it with var outside any functions, you can use window["variableNameHere"] to check if it exists. However, I do agree with the above: you should be defining it as an enclosed object and checking if the "variable name" exists as a key. If you can't access the original variable, at least you can copy it to one you can change.– IceMetalPunk
Jan 2 at 18:20
add a comment |
1 Answer
1
active
oldest
votes
The easiest and less secure way is to use eval(). Never use eval() with user generated data as it's an attack vector.
let test = { setup: function() { return "HelloWorld"; }
let x = eval("typeof test.setup");
console.log(typeof x); // prints function
console.log(x()); // prints "HelloWorld";
You will get an error if ".setup" is evaluated on an undefined variable. So you can use try/catch to handle this.
function exists(value) {
try {
return eval(value);
} catch(e) {
return undefined;
}
}
console.log(exists("typeof test.setup")); // prints a type if it exists, or undefined
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%2f54011006%2fjavascript-does-given-string-exists-as-variable-and-function%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
The easiest and less secure way is to use eval(). Never use eval() with user generated data as it's an attack vector.
let test = { setup: function() { return "HelloWorld"; }
let x = eval("typeof test.setup");
console.log(typeof x); // prints function
console.log(x()); // prints "HelloWorld";
You will get an error if ".setup" is evaluated on an undefined variable. So you can use try/catch to handle this.
function exists(value) {
try {
return eval(value);
} catch(e) {
return undefined;
}
}
console.log(exists("typeof test.setup")); // prints a type if it exists, or undefined
add a comment |
The easiest and less secure way is to use eval(). Never use eval() with user generated data as it's an attack vector.
let test = { setup: function() { return "HelloWorld"; }
let x = eval("typeof test.setup");
console.log(typeof x); // prints function
console.log(x()); // prints "HelloWorld";
You will get an error if ".setup" is evaluated on an undefined variable. So you can use try/catch to handle this.
function exists(value) {
try {
return eval(value);
} catch(e) {
return undefined;
}
}
console.log(exists("typeof test.setup")); // prints a type if it exists, or undefined
add a comment |
The easiest and less secure way is to use eval(). Never use eval() with user generated data as it's an attack vector.
let test = { setup: function() { return "HelloWorld"; }
let x = eval("typeof test.setup");
console.log(typeof x); // prints function
console.log(x()); // prints "HelloWorld";
You will get an error if ".setup" is evaluated on an undefined variable. So you can use try/catch to handle this.
function exists(value) {
try {
return eval(value);
} catch(e) {
return undefined;
}
}
console.log(exists("typeof test.setup")); // prints a type if it exists, or undefined
The easiest and less secure way is to use eval(). Never use eval() with user generated data as it's an attack vector.
let test = { setup: function() { return "HelloWorld"; }
let x = eval("typeof test.setup");
console.log(typeof x); // prints function
console.log(x()); // prints "HelloWorld";
You will get an error if ".setup" is evaluated on an undefined variable. So you can use try/catch to handle this.
function exists(value) {
try {
return eval(value);
} catch(e) {
return undefined;
}
}
console.log(exists("typeof test.setup")); // prints a type if it exists, or undefined
answered Jan 2 at 18:05
cgTagcgTag
24.3k864113
24.3k864113
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%2f54011006%2fjavascript-does-given-string-exists-as-variable-and-function%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
2
Needing to dynamically know the names of variables is often an xy problem and has a pretty strong code smell that leads to needing things like
eval(). If you need to dynamically access something with a string key, that something should be part of a larger data structure, then the problem goes away.– Mark Meyer
Jan 2 at 18:02
1
@MarkMeyer I agree. It's a symptom of a problem.
– cgTag
Jan 2 at 18:08
@MarkMeyer sometimes as developer you do not have the possibilities to change the bigger data structure and have to work with, what was given to you =(
– MasterOfDesaster
Jan 2 at 18:12
1
letandconsthave block scope, but if you declare the variable withvar, it'll have either global or local function scope (depending if it's declared inside a function or not). So if you declare it withvaroutside any functions, you can usewindow["variableNameHere"]to check if it exists. However, I do agree with the above: you should be defining it as an enclosed object and checking if the "variable name" exists as a key. If you can't access the original variable, at least you can copy it to one you can change.– IceMetalPunk
Jan 2 at 18:20