jquery change global variable inside function - javascript

var variable = "before";
change();
alert(variable);
function change(){
variable = "after";
}
Does in possible to change global variable inside function without return ? I need after call function change have output "after"

Yes, it is possible, but remember to NOT put the var keyword in front of it inside the function.
ERORR - DOES NOT WORK:
var variable = "before";
change();
alert(variable);
function change() {
var variable = "after";
}
WORKS:
var variable = "before";
change();
alert(variable);
function change() {
variable = "after";
}

You should avoid declaring global variables since they add themselves as properties to the window. However, to answer your question, yes you can change global variables by setting either changing variable or window.variable.
Example:
http://jsbin.com/xujenimiwe/3/edit?js,console,output
var variable = "before"; // will add property to window -- window.variable
console.log(variable);
change();
console.log(window.variable);
function change(){
variable = "after"; // can also use window.variable = "after"
}
Please let me know if you have any questions!

Related

Use variable in another function then call the new function

Here I'm trying to use a variable in function New(), the variable was created in the function Test().
I'm still a bit confuse about how to use global variable.
function New(){
Test();
//this show nothing
alert(myName);
}
function Test() {
myName = "John";
}
New();
Even when I do "var myName;" outsise of these functions, it doesn't work.
Still searching
Check this fiddle
things to change :
1) use function New(){} instead of function New{}
2) return myName from test function and store it in new variable in New function
function New(){
var myName= Test();
//this show nothing
alert(myName);
}
function Test() {
var myName = "John";
return myName
}
New();
update : yeah u can also define myName as global variable and use it
When you want to declare a variable for use, use the var keyword. When you do this, the location of where you do it determines the "scope" of the variable. If you want to use the variable in two functions, you can simply declare the variable outside of both:
var myVariable = "Something";
function1(){
myVariable = "something else";
}
function2(){
myVariable = "something else again";
}
Another way to share data is to pass that data as arguments into a function:
function1(){
var myVariable = "Something";
function2(myVariable);
}
function2(someName){
alert(someName); // "Something"
}
In your case, you didn't use the "var" keyword to declare your variable, so it became global, but you have a typo in your code, so it didn't run.
Its just a small type error. Just add braces after New
var myName; // have myName global ie, outside all functions
function New(){ // needs the braces() for New to be a function
Test();
alert(myName);
}
function Test() {
myName = "John";
}
New();
Declare myName globally, then define myName in the return of Test() function. When declaring a function, always use keyword "function", "()", and "{}" no matter what.
var myName;
function New() {
alert(Test());
}
function Test() {
myName = "John";
return myName;
}
New(Test);
Global variable is something whose scope is for a particular class and not restricted to a function.
You can create variable myName inside class but outside function and use it anywhere within class.
var myName="";
function New{
Test();
//this show nothing
alert(myName);
}
function Test() {
myName = "John";
}
New();

Swapping variables within a method

I'm trying to learn some OOP, so bear with me. I need to use a variable I defined in one function, elsewhere. Here is my example code (I want INTERCEPT!! to be logged, but it returns undefined):
function Talk() {
var greeting;
var pleaseStop; // declare it
this.A = function () {
greeting = 'hello';
console.log(greeting);
var intercept = function () {
pleaseStop = 'INTERCEPT!';
}
}
this.B = function () {
greeting = 'goodbye';
console.log(pleaseStop); // this returns undefined!
console.log(greeting);
}
}
var activateTalk = new Talk();
activateTalk.A();
activateTalk.B();
This whole code logs the following:
hello
undefined
goodbye
I have also tried intercept.pleaseStop() but it still returns undefined. Would anyone know of a solution?
EDIT:
I've removed the var the second time, but it still returns undefined:
http://jsfiddle.net/d654H/2/
var pleaseStop = 'INTERCEPT!';
You're declaring a new, function-local variable here; drop the var to assign to the existing variable in scope.
Then, you need to actually call intercept; at the moment you only define it.
It's your choice as to when you call that function; in this live example I simply do so immediately after the definition, for the purposes of exposition.
Remove var in front of the assignment to pleaseStop.
This assigns a new value to the pleaseStop declared inside the constructor, which is visible also from inside B:
var intercept = function () {
pleaseStop = 'INTERCEPT!';
}
This declares a new local variable pleaseStop, completely unrelated to the other pleaseStop, that is not visible outside intercept:
var intercept = function () {
var pleaseStop = 'INTERCEPT!';
}
If you do the latter instead of the former, you end up changing the value of another variable than the one you intended.
Your problem is you never set pleaseStop. You have declared intercept as a function, but you never called it. Therefore, pleaseStop is undefined.
Firstly you have't called intercept() anywhere and also u did something
var pleaseStop = 'INTERCEPT!';
which will create new variable instead of initializing global variable
You can do something like this
function Talk() {
var greeting;
var pleaseStop; // declare it
this.A = function () {
greeting = 'hello';
console.log(greeting);
var intercept = function () {
pleaseStop = 'INTERCEPT!';//changed
}
intercept(); //..Added
}
this.B = function () {
greeting = 'goodbye';
console.log(pleaseStop); // this returns undefined!
console.log(greeting);
}
}
var activateTalk = new Talk();
activateTalk.A();
activateTalk.B();
Without var keyword.
var pleaseStop = "A";
function foo(){
pleaseStop = "B"; // overwriting to "B"
}
foo();
alert(pleaseStop); // shows "B"
With var keyword.
var pleaseStop = "A";
function foo(){
var pleaseStop = "B"
// This defines a new variable 'pleaseStop'
// in the scope of function foo(){}.
}
foo();
alert(pleaseStop); // shows "A"
Variable Scope
JavaScript has function-level scope. In most languages which have block-level variable scope, variable are accessible whithin their block surrounded by curly brackets ({and}). But JavaSciprt doesn't terminate scopes at the end of blocks, but terminate them at the end of functions.
I'm sure there are many articles and documents about it. I googled it and found an intresting introductory article.
http://javascriptissexy.com/javascript-variable-scope-and-hoisting-explained/
Hope this helps.

How does scoping work in javascript? Why does this function work?

I simply do not understand how the "reset" function works here, and I created this script! The "value" variable on line 8...how is that reset to zero and then picked up by the iterator("value++") on the next line? I would have thought the iterator, and the whole script, was outside of the function's scope?
var timer = null,
interval = 1000,
value = 48;
$("#start").click(function() {
if (timer !== null) return;
timer = setInterval(function () {
$("#reset").click(function() { value = 0} );
value++;
$("#input").val(value);
}, interval);
});
$("#stop").click(function() {
clearInterval(timer);
timer = null
});
JSFIDDLE
In your example, you don't even need any fancy explanations involving closures or binding.
You've defined value with global scope. The function passed to setInterval repeatedly increments that value and updates the #input element, and the function bound to #reset sets it to zero. Both functions have access to variables with global scope.
The scope of your var value is accessible by all other functions inside that function
(the document ready in your case (if you have it at all, otherwise it's totally a global var name.)). Another way is to define your var to the window Object** which will make it also global to all outer and other functions
Examples with the "usual" way and with some Immediately Invoked Functions Expressions to see clearly the difference:
var text = "Hello!"; // Global
(function sayhello(){
alert(text); // Ok, works
})();
http://jsbin.com/apuker/2/edit
(function defineVar(){
var text = "Hello!"; // Private
})();
(function sayhello(){
alert(text); // No dice
})();
http://jsbin.com/apuker/4/edit
(function defineVar(){
window.text = "Hello!";
})();
(function sayhello(){
alert(text); // Watta?... IT WORKS!
})();
and BTW, Your code should look like: (note the #reset and the nicer if (timer) return;)
var timer = null,
interval = 1000,
value = 48;
$("#start").click(function() {
if (timer) return; // return - if timer is not null (true).
timer = setInterval(function () {
value++;
$("#input").val(value);
}, interval);
});
$("#reset").click(function() {
value = 0;
});
$("#stop").click(function() {
clearInterval(timer);
timer=null;
});
In your example, value is defined at the global scope so it can be accessed anywhere. So upon clicking the element reset, the global value is set back to 0.
Changing it to:
$("#reset").click(function() { var value = 0} );
would create a seperate value variable scoped only to that function.
As of ECMAScript 5, there is only function scope. All variables are global by default, unless declared using the 'var' keyword in which case they are only visible in the function they were declared.
In your script, although you declare 'value' using the var keyword, you declare it outside of any function effectively making it a global variable.
FYI:
There are currently plans to introduce the ability to declare variables with block scope in ECMAScript 6 via the new 'let' keyword.

Is this a javascript closure?

I have this....
function MyFunction() {
var myVar = "I think I am encapsulated";
this.getMyVar = function() {
return myVar;
}
}
var myProperty = new MyFunction();
console.log(myProperty.getMyVar());
myProperty.myVar = "you're not encapsulated";
console.log(myProperty.getMyVar());
It outputs: "I think I am encapsulated twice". Why? I did not think this was a closure...
The closure is around the "getMyVar" function. The variable "myVar" inside the constructor is a local variable, and not visible outside the function except as the return value from "getMyVar".
Setting a "myVar" property on the object does just that, but the "getMyVar" function is not returning a property of an object; it's returning the value of the local variable in the closure.
Yes, it is.
When you define a function inside of another function, the inner function has access to all of the outer function's local variables...
In your case, getMyVar has access to myVar - through the closure.
var myVar = "I think I am encapsulated";
this.getMyVar = function() {
return myVar;
}
This is a closure, and the myVar variable from the time the function was created will be returned. Notice that's it a local variable, so there's no other way to access it after this function exits.
var myVar = "I think I am encapsulated";
Notice that this is not this.myVar (the variable you're setting later with myProperty.myVar).
Probably what you're trying to do is:
function MyFunction() {
this.myVar = "I think I am encapsulated";
this.getMyVar = function() {
return this.myVar;
}
}

Passing local variables from a function out to become global variables

I've spent the last two hours trying to figure out how to do this but nothing is working. Here is a short sample of some of my code. I want to get arrtime and several other similar variables out of the function so I can use them globally. Any ideas? Nothing too complicated please, I'm no expert (obviously).
function showTest(str) {
........
var arrayvals = JSON.parse(xmlhttp.responseText);
var arrtime= (arrayvals[0]);
}
var testvar=arrtime;
document.getElementById("testing").innerHTML=testvar;
The clean way to do this is using js-object notation:
function showTest(str) {
//other code
return {arr: arrayvals, tm: arrtime};
}
var func_result = showTest("blah-blah");
var testvar =func_result.tm;
var testvar2=func_result.arr;
But it's generally a bad idea to have global vars. Why do you need it?
Update sample code with global object
globals = {};
function q(){
globals['a'] = 123;
globals[123] = 'qweqwe';
}
function w(){
alert(globals.a);
//alert(globals.123); //will not work
alert(globals[123]); //that's OK.
}
q();
w();
You can declare the variables outside of the function.
var arrtime, arrayvals;
function showTest(str) {
arrayvals = JSON.parse(xmlhttp.responseText);
arrtime= (arrayvals[0]);
}
var testvar=arrtime;
alert (testvar);
var testvar;
function showTest(str) {
........
var arrayvals = JSON.parse(xmlhttp.responseText);
var arrtime= (arrayvals[0]);
testvar = arrtime;
}
alert (testvar);
The global is to be declared outside of the score of the function but assigned inside the scope of the function.
You simply have to omit var which indicates a variable that is only accessible from the function scope.

Categories

Resources