Pass name of global var to function that alters var? - javascript

I encountered a strange problem today.
The good: I successfully changed a global var value from within a function(in other words the below example works fine when "passedVarName" is substituted with "a").
The bad: When trying to pass the global var name "a" (rather than putting it directly in the function) it fails to work.
Below is what I can't seem to get working:
(on click document should write "2" but instead writes "NaN" ?)
Javascript:
var a = 1;
function click(passedVarName){
passedVarName ++;
document.write(passedVarName)
};
HTML:
Click this Button to alter global var "a".

This is a pretty bad Code Smell, but if you know it's global, then this'll work:
var a = 1;
function click(passedVarName){
window[passedVarName]++;
document.write(passedVarName)
};

Click this Button to alter global var "a".
This passes string 'a' to your function, not the variable a.
You need to pass it as click(a);
Corrected example :
http://html-bin.appspot.com/aghodG1sLWJpbnIMCxIEUGFnZRjhjxoM
[ Did not use jsfiddle.net to avoid confusion by seperating javascript and HTML ]

Passing a global variable as a param to a function creates a copy of that var inside the function. The global doesn't change.
This example will generate the same output everytime you click on the first div:
//html
<div onclick="foo(a)">Click here</div>
<div id="txt"></div>​​​​​​​​​​​​​
//js
window.a = 152;
window.foo = function(varr) {varr++; $("#txt").html(varr)}​
However, it seems like if you pass your variable as a property of an object, pass that object to the function, and inside your function modify the variable, it has global effect :
//html
<div onclick="foo(a)">Click here</div>
<div id="txt"></div>​​​​​​​​​​​​​​​​
//js
window.a = { val:152};
window.foo = function(varr) {varr.val++; $("#txt").html(varr.val)}​
Here is a jsFiddle that works: http://jsfiddle.net/2Ahdb/3/

Forgive me if I misinterpret your knowledge of programming, but a global variable is something that can be accessed and modified by any part of your programming, you do not need to pass it through a function to modify it.
IF you are trying to modify global variables through a function, javascript has some limitations. Only objects are passed by reference.
var a = 5;
var b = { value: 5 };
function changeMe(x) {
x = 10;
}
changeMe(a); //... still 5
function changeMeAlso(x) {
x.value = 10;
}
changeMeAlso(b); //.. changed to { value: 10 }

Related

How to get variables names inside a javascript function

I want to get "a, b" in this example https://jsfiddle.net/8dw9e5k7/ instead I get something else. Is it possible ?
function test() {
a = 5;
b = 10;
try {
var variables = ""
for (var name in this)
variables += name + "\n";
alert(variables);
} catch(e) {
alert(e.message)
}
}
test();
Assigning non-existent variables in a function makes the variables global which means attached to the window object. That's why your code works somewhat and displays the variables along with many other things, because this refers to window.
Dumping your own variables attached to window is not possible in a clean way (some hacks still exist which consist in creating a fresh window with an iframe and compare it to the current window, check this answer if you're interested)
Now if you're expecting this to refer to the lexical scope of the current function, it's not the case and you can't retrieve it programmatically at all.

How to access variables inside function based on string variable representation

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.

can't get object variable with "this" property in object function called by setTimeout() function

I have another question again. I'm currently working with objects and I'm now in very big problem :D. How can I get object variable with "this" property in object function called by setTimeout() function?
HTML:
variable value: <span class="log"></span>
JavaScript:
var logEl = document.getElementsByClassName("log")[0];
var Object = function()
{
this.variable = "abc";
setTimeout(this.callVar,1000);
}
Object.prototype.callVar = function()
{
logEl.innerHTML = this.variable;
}
var obj = new Object();
I want to get variable value: abc, but I still get undefined. How to fix it? setTimeout() must be in code.
Also, I don't want to replace this. with obj., just another solution like parentObj.this....any help will be great!
Fiddle
When setTimeout calls a function, it calls it in the context of the "global" object (window). In JavaScript, this is set based on how the function is called.
JavaScript has .bind() to fix this problem. Try this:
var Object = function()
{
this.variable = "abc";
setTimeout(this.callVar.bind(this), 1000);
}
This will make sure that when setTimeout runs your function, it'll be called in the right "context".
P.S. Don't name a variable Object. JavaScript has a built-in Object and replacing that may have unexpected consequences.

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;
}());

update the global variable in jquery

How can I update the variable value in jQuery? How can I update the variable value as it updates in functions? I checked the scope of variable in jQuery but I did not understand.
<script>
$(document).ready(function(){
var s = 9;
function data()
{
var s = 11;
}
data();
alert(s);
});
</script>
I want 11 in alert for data but I am getting 9. how can I update the value if its updated in functions. please help me out for this.
I think you meant 11 not 80, or maybe you're not explaining it correctly.
Here s is global var, you can modify its value in data function. When you use var s in data function it creates a new variable names s whose scope is limited to that function only. That's why you get 9 outside its scope.
$(function(){
var s = 9;
function data()
{
s = 11; //removed var from here, if you use var here it will...
//create new variable whose scope will end outside this function.
}
data();
alert(s);
});
Recommend reading:
Values, variables, and literals
var in JavaScript and its scope
First of all, this isn't a question about jQuery. The "$(document).ready"... wrapper in your code isn't relevant to the question.
Secondly, like I said in my comment, I'm assuming that the "70" and "80" in your question are mistakes and you meant to say "9" and "11".
To answer your question, you need to remove the var before s = 11. This code should do what you want:
var s = 9;
function data()
{
s = 11;
}
data();
alert(s);
When you add "var", you're telling the code that s should only exist within the scope of the current function (data), and overrides any other variables called "s" in outer scopes. Without "var", the two ss refer to the same variable.
I'd recommend researching "scope in Javascript" and learning more about how "var" and variable scope work.
Hi i don't think that u can get 70 in alert from this script.
and we can't get 80 in alert with these values, from this script u will get 9 in alert box, because u defined var s as two times, one is global and other one is private, when u are going to alert then script take the global. u can get 11 in alert box by using the following script:
<script>
$(document).ready(function(){
var s = 9;
function data()
{
s = 11;
}
data();
alert(s);
});
</script>

Categories