How to declare a dynamic local variable in Javascript - javascript

I want to create a local variable dynamically. JavaScript: Dynamically Creating Variables for Loops is not exactly what I am looking for. I dont want an array. I want to access it like a local variable.
Something like:
<script type="text/javascript">
var properties = new Object();
properties["var1"] = "value1";
properties["var2"] = "value2";
createVariables(properties);
function createVariables(properties)
{
// This function should somehow create variables in the calling function. Is there a way to do that?
}
document.write("Outside the function : " + var1 + "<br>");
document.write("Outside the function : " + var2 + "<br>");
</script>
I tried the following code.
<script type="text/javascript">
var properties = new Object();
properties["var1"] = "value1";
properties["var2"] = "value2";
createVariables(properties);
function createVariables(properties)
{
for( var variable in properties)
{
try
{
eval(variable);
eval(variable + " = " + properties[variable] + ";");
}
catch(e)
{
eval("var " + variable + " = '" + properties[variable] + "';");
}
}
document.write("Inside the function : " + var1 + "<br>");
document.write("Inside the function : " + var2 + "<br>");
}
document.write("Outside the function : " + var1 + "<br>");
document.write("Outside the function : " + var2 + "<br>");
</script>
But the generated variables are not accessible outside the createVariables().
Now, I have this solution.
<script type="text/javascript">
var properties = new Object();
properties["var1"] = "value1";
properties["var2"] = "value2";
function createVariables(properties)
{
var str = "";
for( var variable in properties)
{
str += "try{";
str += "eval('" + variable + "');";
str += "eval(\"" + variable + " = properties['" + variable + "'];\");";
str += "}";
str += "catch(e){";
str += "eval(\"var " + variable + " = properties['" + variable + "'];\");";
str += "}";
}
return str;
}
eval(createVariables(properties));
document.write("Outside the function : " + var1 + "<br>");
document.write("Outside the function : " + var2 + "<br>");
</script>
This works. But I am looking for an alternative/better solution. Is it possible to do it without eval?
EDIT: 04-July
Hi,
I tried a solution similar to what #Jonathan suggested.
<script type="text/javascript">
var startFunc = function(){
var self = this;
self.innerFunc = function innerFunc(){
var properties = new Object();
properties["var1"] = "value1";
properties["var2"] = "value2";
properties["var3"] = "value3";
function createVariables(caller, props) {
for(i in props) {
caller[i] = props[i];
}
caller.func1();
}
createVariables(self, properties);
console.log( var1 );
}
self.func1 = function func1(){
console.log( "In func 1" );
console.log( var2 );
}
innerFunc();
console.log( var3 );
}
startFunc();
</script>
This all works fine. But it is actually creating global variables instead of creating the variables in the function.
The "self" passed to the createVariables() function is window. I am not sure why it is happening. I am assigning the function scope to the self. I am not sure what is happening here. It is anyway creating global variables in this case.
If my question is not clear,
What I am after is creating local variables in the caller. The scenario is like
1) I am inside a function.
2) I invoke another function which returns me a map[This map contains name and value of a variable].
3) I want to dynamically create all the variables, if they are not already defined. If they are already defined [global/local], I want to update them.
4) Once these variables are created, I should be able to access them without any context.[Just the variable name]
<script type="text/javascript">
function mainFunc()
{
var varibalesToBeCreated = getVariables();
createVariables(varibalesToBeCreated);
alert(var1);
alert(var2);
}
function createVariables(varibalesToBeCreated)
{
// How can I implement this function,
// such that the variables are created in the caller?
// I don't want these variables this function.
}
function getVariables()
{
var properties = new Object();
properties["var1"] = "value1";
properties["var2"] = "value2";
}
mainFunc();
</script>

Depending on the scope you'd like the variables to have, this could be accomplished in a few different ways.
Global scope
To place the variables in the global scope, you could use window[varName]:
function createVariables(variables) {
for (var varName in variables) {
window[varName ] = variables[varName ];
}
}
createVariables({
'foo':'bar'
});
console.log(foo); // output: bar
Try it: http://jsfiddle.net/nLt5r/
Be advised, the global scope is a dirty, public place. Any script may read, write, or delete variables in this scope. Because of this fact, you run the risk of breaking a different script that uses the same variable names as yours, or another script breaking yours.
Function scope (using this)
To create variables in a function's scope (this.varName), you can use bind:
var variables = {
'foo':'bar'
};
var func = function () {
console.log(this.foo);
};
var boundFunc = func.bind(variables);
boundFunc(); // output: bar
Try it: http://jsfiddle.net/L4LbK/
Depending on what you do with the bound function reference, this method is slightly vulnerable to outside modification of the variables. Anything that can access boundFunc can change or refer to the value of the values by using boundFunc.varName = 'new value'; This may be to your advantage, depending on use case.
Function scope (using arguments)
You can use apply to pass an array of values as arguments:
var variables = [
'bar'
];
var func = function (foo) {
console.log('foo=', foo);
};
func.apply(null, variables);
Try it: http://jsfiddle.net/LKNqd/
As arguments are ephemeral in nature, nothing "outside" could interfere with or refer back to the values, except by modifying the variable array and re-calling the function.
Global scope as temporary
And here's a small utility function that will make temporary use of the global scope. This function is dangerous to code that also uses the global scope -- this could blast over variables that other scripts have created, use at your own risk:
var withVariables = function(func, vars) {
for (var v in vars){
this[v] = vars[v];
}
func();
for (var v in vars){
delete this[v];
}
};
// using an anonymous function
withVariables(
function () {
console.log('anonymous: ', foo);
},
{
'foo':'bar'
}
); // output: bar
// using a function reference
var myFunction =function () {
console.log('myFunction: ', foo);
};
withVariables(myFunction, {
'foo':'bar'
}); // output: bar
console.log(foo); // output: undefined
Try it: http://jsfiddle.net/X3p6k/3/
Documentation
bind on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind
apply on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
window on MDN - https://developer.mozilla.org/en-US/docs/Web/API/Window

Here is working sample based on Chris Baker answer: Function scope (using arguments)
function myFn() {
function keyList(params) {
var str = '';
for (var key in params) {
if (params.hasOwnProperty(key)) {
str += ',' + key;
}
}
return str.length ? str.substring(1) : str;
}
function valueList(params) {
var list = [];
for (var key in params) {
if (params.hasOwnProperty(key)) {
list.push(params[key]);
}
}
return list;
}
var params = {
'var1': 'value1',
'var2': 'value2'
};
var expr = 'document.write("Inside the function : " + var1 + "<br>")'
var fn;
eval('var fn = function(' + keyList(params) + '){' + expr + '};');
fn(valueList(params));
}
myFn();

I have written short code snippet which will create both local and global variable dynamically
function createVar(name,dft){
this[name] = (typeof dft !== 'undefined')?dft:"";
}
createVar("name1","gaurav"); // it will create global variable
createVar("id");// it will create global variable
alert(name1);
alert(id);
function outer(){
var self = this;
alert(self.name1 + " inside");
}
createVar.call(outer,"name1","saurav"); // it will create local variable
outer.call(outer); // to point to local variable.
outer(); // to point to global variable
alert(name1);
hope this helps
Regards
Gaurav Khurana

The example below demonstrates how with gets a value from the object.
var obj = { a : "Hello" }
with(obj) {
alert(a) // Hello
}
But I want to notice: with is deprecated!

This answer is more or less the same as several answers above but here with a simplified sample, with and without using eval. First using eval (not recommended):
var varname = 'foo'; // pretend a user input that
var value = 42;
eval('var ' + varname + '=' + value);
And alternatively, without using eval:
var varname = prompt('Variable name:');
var value = 42;
this[varname] = value;
I hope this helps.
Source: https://www.rosettacode.org/wiki/Dynamic_variable_names#JavaScript

since you are wanting the scope of where the function is being called pass this to the function
var properties = new Object();
properties["var1"] = "value1";
properties["var2"] = "value2";
function createVariables(context) {
for(i in properties) {
context[i] = properties[i];
}
}
createVariables(this);
console.log( var1 );

Do you need something like this?
function createVariables(properties, context){
for( var variable in properties){
context[variable] = properties[variable ];
}
}
So, calling as createVariables(properties, this) will fill the current scope with values from properties.
<script type="text/javascript">
var properties = new Object();
properties["var1"] = "value1";
properties["var2"] = "value2";
createVariables(properties, this);
document.write("Outside the function : " + var1 + "<br>");
document.write("Outside the function : " + var2 + "<br>");
</script>

Related

Get variable from string

'Im trying to extract multiple variables from a string.
The string "var context = [{data: 'some data'}]; /* Some garbage comment blabla */ var foo = 3;" my code will only look for the variables context and foo.
var stringToEval = "var context = [{data: 'some data'}];/* Some garbage comment blabla */ var foo = 3;";
function evalString() {
eval(stringToEval);
if (context !== null && context !== undefined) {
// Do something
}
if (foo !== null && foo !== undefined) {
// Do something
}
}
My solution uses eval() but since I don't have control of the input this is a security issue.
Is there a way around eval()? or how can I prevent the execution of functions inside eval?
I write some code to do this, based on your string pattern, maybe it refer to you needed:
Working Demo:
https://jsfiddle.net/aw6j9upL/6/
Code:
const stringToEval = "var context = [{data: 'some data'}];/* Some garbage comment blabla */ var foo = 3;";
const contextBadJson = stringToEval.replace(/(.*)(var context = \[)(.*)(\];)(.*)/mg, '[$3]');
const fixBadJSON = (badJSON) => badJSON
// Replace ":" with "#colon#" if it's between double-quotes
.replace(/:\s*"([^"]*)"/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
// Replace ":" with "#colon#" if it's between single-quotes
.replace(/:\s*'([^']*)'/g, function(match, p1) {
return ': "' + p1.replace(/:/g, '#colon#') + '"';
})
// Add double-quotes around any tokens before the remaining ":"
.replace(/(['"])?([a-z0-9A-Z_]+)(['"])?\s*:/g, '"$2": ')
// Turn "#colon#" back into ":"
.replace(/#colon#/g, ':')
;
const context = JSON.parse(fixBadJSON(contextBadJson));
const foo = stringToEval.replace(/(.*)(var foo = )(.*)(;)(.*)/mg, '$3');
console.log(context);
console.log(foo);

How to access variable from a function in Javascript

I want to access variables ie. distance, vertex2Position, path which in two seperate function, inside main function called getResult. How can I achieve this without altering my code or altering my code in minimum way.
function getResult() {
document.getElementById("vertex1").onchange = function() {
var vertex1 = document.getElementById("vertex1").value;
var vertex1Position = graph.node.findIndex(e => e.id == vertex1) + 1;
document.getElementById("output").textContent = vertex1Position;
var distance = execute(vertex1Position); // How can I access distance in my result variable
};
var vertex2Position = 0;
console.log("whats here");
document.getElementById("vertex2").onchange = function() {
var vertex2 = document.getElementById("vertex2").value;
vertex2Position = graph.node.findIndex(e => e.name == vertex2)+ 1; // I also want to access vertex2Position in my result variable which is in outer function
document.getElementById("secondOutput").textContent = vertex2Position;
var path = getPath(vertex2Position); //How can I access path in var result
};
var result = distance.vertex2Position; // I want to store distance and vertex2Position in result variable
document.getElementById("searchResult").innerHTML = "test" + result + "" + path + "."; // I also want to access path
}
You should use something like this :
var container = (function(){
var distance;
var vertex2P;
return {
setDistance: function(distance){
this.distance = distance;
},
getDistance: function(){return this.distance;},
setVertex2P: function(vertex2P){
this.vertex2P = vertex2P;
},
getVertex2P: function(){return this.vertex2P;},
}}());
And then you can get and set the values in other functions like this
var result = function(){
container.setDistance(2);
container.setVertex2P(3);
console.log(container.getDistance() + container.getVertex2P());
}
result(); // 5
These are(maybe ) the best practices you can use in Javascript with this you avoid the global variables and added privacy to your variables, hope it helps you.
P.S you can short this with ECMASCRIPT 6
In javascript, you need understand about scopes. In your code, the
main scope is the getResult() function, so if you want to access
variables inside sub functions (functions inside the getResult()
function), you'll need declare the variables at beginning of this main
scope.
Example:
function getResult() {
var distance,
path,
vertex1,
vertex2,
vertex1Position,
vertex2Position = 0;
document.getElementById("vertex1").onchange = function() {
vertex1 = document.getElementById("vertex1").value;
vertex1Position = graph.node.findIndex(e => e.id == vertex1) + 1;
document.getElementById("output").textContent = vertex1Position;
distance = execute(vertex1Position);
}
document.getElementById("vertex2").onchange = function() {
vertex2 = document.getElementById("vertex2").value;
vertex2Position = graph.node.findIndex(e => e.name == vertex2)+ 1;
document.getElementById("secondOutput").textContent = vertex2Position;
path = getPath(vertex2Position); //How can I access path in var result
};
result = distance.vertex2Position;
document.getElementById("searchResult").innerHTML = "test" + result + "" + path + ".";
}
Note: You're using functions triggered by "onchange" event, so your variables will initiate as undefined, except for "vertex2Position"

for (var o in this) inside an object

I’ve made a little sandbox using the p5.js library : http://gosuness.free.fr/balls/
I’m trying to implement a way to deal with the options on the side, which are toggled using keyboard shortcuts.
This is what I tried to do :
var options =
{
Option: function(name, value, shortcut)
{
this.name = name;
this.shortcut = shortcut;
this.value = value;
this.show = function ()
{
var texte = createElement("span",this.name + " : " + this.shortcut + "<br />");
texte.parent("options");
texte.id(this.name);
}
},
toggle: function(shortcut)
{
for (var o in this)
{
console.log(o);
if (o.shortcut == shortcut)
{
o.value = !o.value;
changeSideText("#gravity",gravity);
addText("Toggled gravity");
}
}
}
};
I instantiate each option inside the object options thus :
var gravity = new options.Option("gravity", false,"G");
var paintBackground = new options.Option("paintBackground",false,"P");
When I call the function options.toggle, console.log(o) gives me "Option" "toggle". but what I want is to get for (var o in this) to give me the list of properties of the object options, which are in this case gravity and paintBackground
How do I do that ?
Thanks !
When You create a instance of Option, its not kept within the variable options, but in the provided variable.
var gravity = new options.Option("gravity", false,"G");
Creates an instance of Option located under gravity variable.
Your iterator for (var o in this) iterates over options properties, with the correct output of the object's methods.
If You want your code to store the new instances of Option within options variable, you can modify code like
var options =
{
instances: [],
Option: function(name, value, shortcut)
{
this.name = name;
this.shortcut = shortcut;
this.value = value;
this.show = function ()
{
var texte = createElement("span",this.name + " : " + this.shortcut + "<br />");
texte.parent("options");
texte.id(this.name);
}
options.instances.push(this);
},
toggle: function(shortcut)
{
for (var i in this.instances)
{
console.log(this.instances[i]);
if (this.instances[i].shortcut == shortcut)
{
this.instances[i].value = !this.instances[i].value;
changeSideText("#gravity",gravity);
addText("Toggled gravity");
}
}
}
};
this is your example working as You intend it to, but i wouldnt consider this as a reliable design pattern.

React loop through object and render div with onClick function which takes argument

So I created a loop which goes through an object created by googles gecoding api. Finds certain values and than puts them into a "results list", the single elements have onClick functions. Now when I do the onClick functions with bind, they do work, when I do them with () => they don't. Maybe someone can explain to me why that doesn't work?
loop:
renderResults: function(){
var status = this.state.data.status;
var results = this.state.data.results;
var ok = (status === 'OK' ? true : false);
if (!status) {
return <div> </div>
}
if (!ok) {
return <div className="searchresults">Error, we couldn't find a match</div>
}
if (status && ok){
var size = Object.keys(results).length
console.log(this.state.data);
var validation_messages = this.state.data.results;
///* Get properties *///
var resul =[];
for (var key in validation_messages) {
console.log("####### " + key + " #######");
// skip loop i the property is from prototype
if (!validation_messages.hasOwnProperty(key)) continue;
var label1 = '';
var label2 = '';
var obj = validation_messages[key];
console.log(obj);
for (var prop2 in obj.address_components) {
if(!obj.address_components.hasOwnProperty(prop2)) continue;
var obj3 = obj.address_components[prop2];
if (obj3.types.indexOf('locality') !== -1) {
label1 = obj3.long_name;
}
if (obj3.types.indexOf('country') !== -1) {
label2 = obj3.long_name;
}
}
var lat = obj.geometry.location.lat;
var lng = obj.geometry.location.lng;
var placeid = obj.place_id;
var label3 = lat.toFixed(3) + "°N / " + lng.toFixed(3) + "°E";
console.log('label1: '+label1);
console.log('label2: '+label2);
console.log('label3: '+label3);
console.log('lat: ' + lat);
console.log('lng: ' + lng);
console.log('id: ' + placeid);
console.log(validation_messages[key].formatted_address);
resul.push(<div className="results" onClick={this.pushlabels.bind(this, label1, label2, label3)} >{label3}</div>);
}
console.log(resul);
return resul;
}
So this works:
resul.push(<div className="results" onClick={this.pushlabels.bind(this, label1, label2, label3)} >{label3}</div>);
This doesn't work:
resul.push(<div className="results" onClick={() => this.pushlabels(label1,label2,label3)} >{label3}</div>);
What do I mean with not working? If I take the version which doesn't work than I get only pushed the label1, label2, label3 from the last object in the loop.
So now I wonder why?
It has to do with variable scoop and closures, for a similar problem have a look at javascript scope problem when lambda function refers to a variable in enclosing loop
Here's a short and simple program that illustrates what happens:
function foo(first, second){
console.log(first + " : " + second)
}
var x = "x";
let bar = () => {foo("bar", x)}
let baz = foo.bind(this,"baz", x)
bar()
baz()
x = "y"
bar()
baz()
//Output:
//bar : x
//baz : x
//bar : y
//baz : x
So basically bind makes the function remember (it actually returns a new function with the parameters set) the current state of the variables. Where as a lamda looks at the variables when it's executed. That's why you only see the last three labels when you don't use bind.

Why do I get a message saying "Object is not a function" when I try to do an apply?

I set up some variables to hold page elements:
this.examStatusSelect = element(by.id('examStatusSelect'));
this.examTypeSelect = element(by.id('examTypeSelect'));
I have this function call:
dom.checkGrid('* check', 0, [
[page.examStatusSelect, 0],
[page.examTypeSelect, 0],
]);
What I wanted to do was make a call to another function like this:
var Dom = function () {
var self = this;
this.getSelectOption = function (element, value) {
var id = element.locator_.value;
return element(by.xpath('//select[#id="' + id + '"]/option[#value = "' + value + '"]'));
}
this.checkGrid = function (label, expectedCount, params) {
it(label + ': Check for ' + expectedCount + ' grid rows', function () {
for (var i = 0; i < params.length; ++i) {
self.getSelectOption.apply(self, params[i]).click();
}
page.retrieveButton.click();
expect(page.row.count()).toBe(expectedCount);
});
}
But I am getting a strange error pointing to the line with the xpath. The error is
TypeError: Object is not a function
I cannot see what this means. Can someone suggest what I might be doing wrong? I'm also not sure what is the purpose of the self after apply( ?
You are redefining element in the local scope. Instead name your input parameter elem for example like so:
this.getSelectOption = function (elem /* local scope */, value) {
var id = elem.locator_.value; /* elem is local scope here */
/* element is from the not local scope
(might be global, could also be from a closure) */
return element(by.xpath('//select[#id="' + id + '"]/option[#value = "' + value + '"]'));
}

Categories