Get a variable from Jquery function - javascript

This is my config in test.js:
var still;
jQuery(function(still){
still = 5;
});
console.log(still);
i want to show on console the variable 'still' (5), but is show to me 'undefined' !
can any1 help me :) !
Thanks

check this code. remove still from function as argument
var still;
jQuery(function(){
still = 5;
});
console.log(still);

This is because your global still variable has been hidden by function's argument with the same name. Try this:
var still;
jQuery(function(stillTheArgument){
still = 5;
});
console.log(still);
Please, reconsider your code as global variables are often not very good idea.

To prevent clogging the global namespace, alternatively you could pass the variable via immediately invoked function expression like so:
The variable still will be available within the scope of the outer function.
(function($, still) {
$(function() {
alert(still);
});
})(jQuery, "STILL");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
You are overriding the current global variable with your function variable as it currently stands.

as charlietfl told consol statement executed first. and at that time value of still is undefined.
try initializing still like this, no need of onReady handler
var still=5;
console.log(still);

Related

Understanding top level window property

I get a js error when I declare the following script.
<script>
window.onload=init;
init = function(){alert("Yahoo!");}
</script>
It works when I declare init as:
<script>
window.onload=init;
var init = function(){alert("Yahoo!");}
</script>
Shouldn't the top level init should implicitly become the property of window object? Please help me understand the concept.
JavaScript tracks variables and function declarations before executing the code. Lots of languages do this, actually, so it's a good thing to get used to.
It does not, however, track assignments. That counts as executing the code. Even though when a variable that is not defined is assigned, it becomes a property of window, it is not a variable! It can be deleted from window, unlike real variables.
var i = 2;
n = 2;
delete window.i; //false
delete window.n; //true
Thus, they can not be used before they are defined like variables. Instead, they must be defined first, and then used. Otherwise, they will not be defined.
//OK, but not recommended because init is now not a variable. It makes more sense to make init a variable instead.
init = function(){alert("Yahoo!");}
window.onload=init;
<script>
window.onload=init;
var init = function(){alert("Yahoo!");}
</script>
This is organized by Javascript as such (variable declarations first):
<script>
var init;
window.onload=init;
init = function(){alert("Yahoo!");}
</script>
Thus, init is present when used for onload.
The one without the var doesn't include a variable declaration but an assignment to a property of window. Assignments are not changed during preprocessing. So, nothing named init is found and execution fails.
this is related to the fact that javascript engine makes two passes over a function. at first pass, it moves all the local variables to the top of the function, and in second pass it runs the function.
So, when you define init with var, it is a local variable, therefore defined in the first pass and successfully run in the second pass.
I'm not sure if i could make it clear, but if you want to get more information on this topic, it was very well covered in Single Page Web Applications by Michael S. Mikowski and Josh C. Powell.

Javascript variable unexpectedly undefined

For this block of code:
if(!skipit)
{
var update_argument='';
if (document.formname.fieldname)
{
update_argument=document.formname.fieldname[document.formname.fieldname.selectedIndex].value;
}
window.setTimeout('updatepcols(update_argument)',250);
return false;
}
I was getting an error in my setTimeout call that "update_argument" was undefined. When I changed the line where I assign it the null string value from "var " to "window.", the error was gone and the code worked. I would guess that there's a scope issue here, but I don't follow it. Why would update_argument be undefined in this case, but putting it in the window object lets me use it? (updatepcols is a function that updates pricing columns.)
Try this instead. Using a closure in this fashion preserves the reference to update_argument
setTimeout(function(){
updatepcols(update_argument);
},250);
I have a funny feeling the script you passed as text, when evaluated, executes in the global scope, i.e. outside the local scope in which update_argument is declared.
setTimeout('updatepcols(update_argument)',250);
I'm not sure if this is a scope issue or not, but altering your setTimeout call should do the trick:
window.setTimeout('updatepcols('+update_argument+')',250);
This fiddle demonstrates: http://jsfiddle.net/mLrqZ/
Change your expression. Should be written like this if you want to pass the local variable to your callback function:
window.setTimeout('updatepcols('+update_argument+')', 250);
or if you want to use a closure instead, then do this:
window.setTimeout(function(){ updatepcols(update_argument) }, 250);
Yeah, like the others say, using a closure is better practice.

Closures in JavaScript

I have a code like this where I am trying to add an event handler to some button. I would like to use a global variable & store its current value in callback closure & not its reference.
var globalNum="dummy";
function A()
{
$("#button").click(function()
{
$("#button").append(globalNum);
});
}
globalNum="dummyAgain";
Now if click event is fired what would be added - "dummy" or "dummyAgain" ?
I believe it would be "dummyAgain" coz for closure global variable's reference is stored. I want value to bind.
I know I can create a local variable inside A which I can initialize with global variable & bind that but is there some other cooler way around too?
Thanks
You are right, it would append dummyAgain. You can deal with this by using bind() and send some event data:
var globalNum="dummy";
(function A()
{
$("#button").bind('click', {localNum: globalNum}, function(e)
{
$("#button").append(e.data.localNum);
});
})();
globalNum="dummyAgain";
Note that I immediately execute the function A, so the click handler gets attached before the value of globalNum changes. As #Andrew points out in his comment, this is the same effect as not using the "wrapping" function A at all.
Same solution without bind:
(function()
{
var localNum = globalNum;
$("#button").click(function()
{
$("#button").append(localNum);
});
})();
Here the anonymous function is useful to capture the the current value globalNum in a local variable.
Update:
For the sake of completeness (I hope, #Andrew, you don't mind that I put it here). The "coolest" way is probably to use a parameter for the function and execute the function immediately with this parameter:
var globalNum="dummy";
(function(globalNum)
{
$("#button").click(function()
{
$("#button").append(globalNum);
});
})(globalNum);
globalNum="dummyAgain";
The "trick" is that the name of the parameter and the name of the global variable are the same.
This is also very often used to refer to some object with a shorter identifier without polluting the global namespace, e.g. with jQuery:
(function($) {
// jQuery == $
})(jQuery)
Maybe there is some cooler way, but declaring a local variable inside A is the most simple and direct way, hence the best.

Do jQuery and JavaScript have different namespaces?

I have this code in jQuery..
$(document).ready(function(){
var fieldCounter = 0; ...
I have a jQuery function that increments this value.
This works, but I can't access this value on the page from a non-jQuery function? The reverse is also true, if I scope it in JavaScript e.g.
<script type="text/javascript">
var fieldCounter = 0;
I can access it from javascript but jQuery can't view it?
I'm probably doing something really dumb?
It has nothing to do with jQuery, but all with Javascript scope.
$(document).ready(function() {
var fieldCounter = 0;
});
fieldCounter is declared inside a function. Since Javascript has function scope, the variable is not visible outside the function.
BTW, jQuery is Javascript, they play by the same rules, they're not two different technologies.
Exhaustive answers can be found here: What is the scope of variables in JavaScript?
jQuery is not magic. It is a JavaScript library. Your issue is that you're defining a local variable inside a function. Due to the way JavaScript lexical scoping works, you can't access it outside that function (with the exception of closures, which does not apply here).
Most likely, you just want:
$(document).ready(function(){
fieldCounter = 0;
That will make it a global variable.
Edit: Note that using a namespace and/or declaring the global variable is cleaner, but not required.
Your problem in the first case is scope. By putting the var init inside a function declaration, you've scoped it to access inside that function.
Something else is going on in the second case; more code would be necessary to see what.
The global scope in Javascript is window. That means that when you declare variables directly in <script> tags, you can get them back by asking for window.variableName.
A common way to resolve these kinds of scoping issues is to create a namespace framework. If you do it right you can call myNamespace.subNamespace.variable and have full confidence that because it's explicitly scoped to window, you can get it back no matter where you are.
Remember that jQuery is built in Javascript. There's nothing special about it.
JavaScript has function scope.
var count = 8;
var myfunction = function() {
var newCount = count + 1;
};
alert(newCount); // undefined
it's because of the scope of javascript... try to read this
Variables declared inside jQuery code block will have local scope.If you need to access a variable both in local javascript function as well as jQuery code block then declare the variable at global level. Sample Code snippet :-
<script type="text/javascript" language="javascript">
var increment = 0;
$(document).ready(function() {
$("#button2").click(function() {
increment = increment + 1;
alert(increment);
});
});
function ClickMe() {
increment = increment + 1;
alert(increment);
}
</script>

Need some help understanding this JavaScript

I have the following strange looking code in a js file and i need some help in understanding whats going on. What im confused about is why is the whole thing put in paranthesis ?. What does that mean ?
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
}
});
If the code that you provided is complete (with the exception of what is inside the two $(document).ready(function() {}); statements), than this code does nothing and the function is never executed. It's the same with or without the wrapping parenthesis.
By wrapping a function in parenthesis, you can create an anonymous function. However, the function must be executed immediately, or stored in a variable (which would negate the anonymous part). You'll often see this technique to avoid polluting the global scope with variables that are temporary or only used for initialization of a larger application. For example.
(function() {
// Do initialization shtuff
var someLocalVariable = 'value';
})();
// Notice the `();` here after the closing parenthesis.
// This executes the anonymous function.
// This will cause an error since `someLocalVariable` is not
// available in this scope
console.log(someLocalVariable);
So then, what your code is missing is the (); after the closing parenthesis at the end of the function. Here is what your code should (presumably) look like:
(function() {
var someobj = window.someobj = [];
var parentId = '#wrapper';
$(document).ready(function() {
//some code here
});
$(document).ready(function() {
//some code here
});
})();
It does not look like this code is complete. As written, this code will do nothing at all. Are you missing a close paren and an extra set of parentheses at the end?
In JavaScript, there is no module system, and thus no way to create a module with its own top-level definitions that don't conflict with other modules that might be used.
In order to overcome this, people use anonymous function definitions to avoid name conflicts. What you do is create an anonymous function, and execute it immediately.
(function () { /* do stuff */ })();
This creates a function, and then executes it immediately with no arguments. Variables defined using var within that function will not conflict with variables defined anywhere else, and thus you get the equivalent of your own, private namespace, like what a module system would provide.
The outer parentheses are redundant here (there is a typo in your code though, I think you're missing the closing );). Sometimes people will wrap a function in parentheses for clarity when invoking the function immediately, e.g.
(function($) {
//some jQuery code
})(jQuery);
Within the function above, the parameter $ will have the value of the outer jQuery variable. This is done within jQuery and jQuery plugins to prevent the $ symbol clashing with other frameworks.
I'm going to assume that this is actually part of an anonymous function definition and that's why it's in parenthesis. I could see doing this if there was some sort of logic going to make window.someobj change based on different conditions, but have code further along do the same thing.
The parenthesis aren't actually necessary as far that this code goes. This code doesn't seem complete though. The function initializes by setting a variable to some object on the page and then setting another constant. Then there are two seemingly identical triggers that will trigger some code on page load.
Doesn't seem like a very useful piece of code. Is there some larger portion that might shed some light on this?
In JS, You can declare a function and automatically call it afterwards:
( function Test() { alert('test'); } )();
The parentheses define a temporary scope. It is sometimes useful to do so in JavaScript. There are a number of examples and further explanation in John Resig's excellent guide to learning advanced JavaScript:
http://ejohn.org/apps/learn/#57

Categories

Resources