How to access variables inside function based on string variable representation - javascript

I have following function
function myFunction(){
var foo="My Foo String";
}
I would like to access my variable in a following way
function myFunction(){
var foo="My Foo String";
console.log(SOMETHINGIDONOTKNOWABOUT["foo"]);
}
I know in javascript its possible to use window["yourvariablename"] to access it, but I am interested to access function variable in similar way, therefor
Is there a way to access a javascript variable using a string that contains the name of the variable? is not a duplicate.
Eval is not correct answer for me.

Don't do this. Dynamic variables are really annoying to debug and optimize by the browser.
Use a set, a map, create a class for it, or even a simple object to store things you want to be able to access with a string.
function myFunction() {
var myData = {
"foo": "My foo string"
};
console.log( myData[ "foo" ] );
}

If I understand you question properly, you should use foo without quotes:
window[foo]
Just note that putting values on the global scope is a bad practice.

Is the following snippet the kind of things you are trying to achieve?
If you want to use a variable as an array element name, you don't have to use quotes. i.e. array["foo"] should be array[foo] if foo is a variable.
var array = [];
array['foo'] = 'bar';
// Code #1
function myFunction(element) {
console.log(array[element]);
}
myFunction('foo');
// Code #2
function myFunction() {
element = 'foo';
console.log(array[element]);
}
myFunction();
Hope it helps, in any way.

Related

Modify variables inside a function with javascript

I'd like to know if it is posible, having one or more variables to pass them into a function and get those variables modified. I think it is posible with objects, as they behave as references, but I don't know.
With 1 var you could do:
var something = increase(something);
but what if you have, for example, 2 variables with recipies, and would like to exchange them?
exchange_recipies(book1, book2);
You could do this but the variables are parameters inside the function... So is there another way that I'm missing?
EDIT: I know it can be done in many ways but I'll state some here that I don't like due to obvious limitations:
-Use global variables.
-Use objects
-Return an array and reasign.
EDIT2: this Is it possible to change the value of the function parameter? helped me, but I think that answer is uncomplet and there are ways of doing this.
If the variables are declared globally then you wouldn't need to pass them into the function since they can be addressed inside the function.
var something = 1
function bar(){
something = increase(something);
}
For example.
This means you avoid changing the variables into parameters and can then address them from any function (dependant on nesting, ergo, if the variable is declared inside a function it can't be addressed outside of that function but can from a function inside)
function foo(){
var something = 1
function bar(){
//works because it exists in the parent function
something = increase(something)
}
}
function foobar()
//Something doesn't exist here so would return something = undefined
something = increase(something)
}
One way to do this is pass these two parameters as objects:
exchange_recipies({ obj: book1 }, { obj: book2 });
and then inside finction you can operate on obj properties
function exchange_recipies(book1, book2)
{
book1.obj = book2.obj;
...
}
http://codepen.io/anon/pen/eNRZZb

Reading a variable value inside a named function in javascript

This may be very simple but i lost my way in finding the answer,
I have a named function inside a Backbone view. I'm trying to write unit test for this named function and i could see a variable is being declared in function scope. The state of this variable changes based on certain scenarios.
I have instantiated the view object inside my test suite and when i do a console.log(viewObject.namedFunction) i see the entire function being logged properly. Now how do i access the variable inside the namedFunction, i was expecting something like viewObject.namedFunction.variableName but it will not work and when i did that, it was not working as expected.
If the variable is tied to viewObject scope then it would have been easy to access it. But in this scenario it is not so can some one please help me in getting a hold on the variable inside named function in view object from test suite.
I think I understand your confusion, because when you define a variable using var in the window scope, it becomes a property on the window object... It would seem to follow that when you define a variable in a child scope, it should become a member of the local context, right? Nope. Globals are special ;-)
In fact, if that were the case, there would be no privacy!
If you want sign to be public, be explicit.
obj = {
namedFunction : function myself() {
console.log(myself);
myself.sign = 23;
}
};
obj.namedFunction.sign;
The only problem with this approach is that you can now assign a new value to sign from anywhere. The classic and preferred approach to this problem is to create a getter function for your private variable.
var obj = {
namedFunction : function myself() {
var sign = 3;
myself.getSign = function(){return sign;};
}
};
obj.namedFunction.getSign();
This isn't by any means the only approach, but I hope it was helpful.
One way to do this is like such:
namedFunction = (function(){
var theActualFunction = function(){
//Do something
//Access variable like: theActualFunction.MyVariable
};
theActualFunction.MyVariable = "value";
return theActualFunction;
}());

Javascript - Calling a function name based on a variable

I am trying to call a function whose name is defined elsewhere is the code.
Below is sample code:
Inner.testFunc = function(node) {
var functionName = node.substring(node, to.indexOf('#'));
// call the function based on functionName
[functionName + '()']
}
function something() {
//doing something
};
...
Assuming that functionName = something, this should try to call the function, but it isn't doing it.
I'm tried using other links such as Call javascript function which name is in variable but it didn't help.
I've also tried using eval():
eval(functionName + '()');
but this returned something about an illegal character...
Your eval call might not be working; use instead:
eval(functionName)(); //note () after the eval statement
In your code ensure first that functionName is something
console.log(functionName === 'something') //true
If your function is defined in the global scope, you could take advantage of the fact that global variables and global functions can be accessed as properties of the global scope:
function something(){ console.log('Works!'); }
window['something'](); // Works!
If it is not, perhaps a reference to it is stored as a property of an object:
var x = { something : function(){ console.log('Also works'); } };
x['something'](); // Also works
Otherwise, it is impossible to access.
functionName is the return of the substring method, not the function itself.
You can create a map of functions with their names as keys as shown below. And then you can pass the output of substring to the map and call the function.
function myName() {
console.log("thefourtheye");
}
var functions = { // map of functions and their names
name: myName
};
functions["name"](); // Instead of "name" pass the result of substring
It's a little more verbose but what about using a case statement to run a function based on the value of node.

Use argument as variable name (Javascript)

I can't seem to find a question that answers this directly.
I'd like to use a function argument as the name of a variable within that function.
e.g.,
test(var1);
function test(foo)
{
var foo = 'Hello world!'; // Set var1
}
alert(var1); // Hello world!
Can I use the brackets here (i.e., window.[ ])?
Yeah, you can use brackets:
window[foo] = "Hello World"
Here's a JSFiddle
Er...okay, so this is almost certainly not a good idea.
Short answer: sorta. If you're running in a browser, you can do this:
var polluteGlobalNamespace = function(symbol) {
window[symbol] = "whatever";
};
polluteGlobalNamespace('foo');
console.log(foo);
But that only works for global variables. There is no way to do this with function-scoped variables, because JavaScript lacks first class environments.
But unless you're doing some deep dark metaprogramming, this isn't a good idea. It might be better to post the problem that you're trying to solve with this function to see what the idiomatic way to do it is.

JavaScript unable to reference this object

I am trying to reference this.foo in an object I created, however this is referencing the HTML element that triggered the function. Is there any way that I can preserve the references to this in an object when it is called via an event?
Here is an example of what is going on:
$('document').on('click','button',object.action);
var object = {
foo : null,
action : function(){
this.foo = "something";
}
};
The error I would receive is
Uncaught TypeError: Object #<HTMLInputElement> has no variable 'var'
If you want to preserve this, you should probably attach your event like that:
$('document').on('click','button',function() { object.action() });
Also, if you use this object as it is presented in the question, you may as well use object instead of this:
var object = {
foo : null,
action : function(){
object.foo = "something";
}
};
Also you might want to familiarize yourself with the Bind, Call, and Apply - jQuery uses these behind the scenes to replace your this with HTML Element;
Also, var is a reserved keyword and you should not use it for a property name; if you really want to do that, use a string "var" and access it via [] notation like this:
var a = {"var": 1}
a['var']
var ist reserved word in JavaScript.
This works fine:
$(document).ready(function(){
var myObj = {
myVal: null,
action:function(){
this.myVal = "something";
}
};
myObj.action();
console.log(myObj.myVal);
});
Here link to JS Bin
I hope i could help.
Change this.var to object.var
The problem that this refers to context of where it was called from.
You call object.action from click event on button, so this is #<HTMLInputElement> here.
And, as it was already said, don't use reserved words like var as variable names
You can pass object as the this value using .apply():
$('document').on('click','button',function(){object.action.apply(object); });
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply
Your this should be referencing object but it is not most likely because of the use of var which is a reserved word in JavaScript.

Categories