Unable to understand certain concepts in JavaScript - javascript

In the website the following lines are given:
Your global variables (or functions) can overwrite window variables (or functions).
Any function, including the window object, can overwrite your global variables and functions.
I am unable to understand what this says.

Above that paragraph you can find this:
Global Variables in HTML
With JavaScript, the global scope is the complete JavaScript environment.
In HTML, the global scope is the window object. All global variables belong to the window object.
Combined with the quote in your question - it means that because the global scope is actually the window object - it's possible to override global functions/variables.
Here is an example:
console.log(window.Math.PI);
Math = {
PI: 5
}
console.log(Math.PI);

The browser puts certain "global" (i.e. accessible anywhere in any file) functions and variables on the window object. One such example is the function window.setTimeout, which executes its argument after a given delay.
You can also access these global window.* variables without the window prefix at all, i.e.
window.setTimeout === setTimeout
That means if you assign to a global variable with a conflicting name, you can 'override' the browser defaults -
window.setTimeout === setTimeout
setTimeout = 'myString'
window.setTimeout === 'myString'
That's why it's generally best practice not to create variables in the global (window) scope.

Related

Variables declared in the global scope - why are they equivalent to properties on the global obejct? [duplicate]

var foo = 'bar';
console.log(window.foo); // bar
Seems like variables get assigned as properties to this, but inside anonymous functions, this refers to the parent scope, but doesn't assign variables to the parent scope.
function() {
var foo = 'bar';
}();
window.foo; // undefined
What object do variables get assigned to in non-global scopes?
To cite http://perfectionkills.com/understanding-delete/#execution_context:
Every execution context has a so-called Variable Object associated
with it. Similarly to execution context, Variable object is an
abstract entity, a mechanism to describe variable instantiation. Now,
the interesing part is that variables and functions declared in a
source text are actually added as properties of this Variable object.
When control enters execution context for Global code, a Global object
is used as a Variable object. This is precisely why variables or
functions declared globally become properties of a Global object
Yet, these Variable Objects are not accessible. The only non-internal one is the global object, window or this (in global context).
The relevant section in the specification is #10: Executable Code and Execution Contexts.
In JavaScript, all variables are assigned to some scope object. However, only the scope object of global variables is accessible in JavaScript in the browser through the window object. Variables in a function scope are assigned to some scope object used internally by the JavaScript runtime, but this cannot be accessed by the user.
In another environment, global variables may be accessible as properties of another object (such as GLOBAL in node.js) or may be inaccessible (such as application scripts running inside the Windows Script Host).
They're available only in the function they're declared in.
Function scope is the only other scope in JavaScript, btw, unlike block-scoping in other {} languages.)
Re: your edit Don't be fooled--JS's this semantics are a bit irksome IMO--this may not be what you expect under a variety of circumstances.
Inside self-invoking anonymous function eg:
function() {
....
}()
All variables remain inside it and do not attach themselves to global object or window. Using that technique, there are patterns created such as module/singleton pattern.
Notice that in JS, variables have function-level scope.

How does the identifier resolution work in Javascript?

Can someone please explain how identifier resolution works for Javascript taking the following scenarios :
A global function is called .
A function inside an user defined javascript object is called .
You have to learn the context and scoping in ECMA Script to understand this. And in between is it identifier or variable?
Identifiers are normally tagged to window object. Say String() it's actually window.String().
Normally when a page loads the all the variables and functions are added as properties to the window object. The window object becomes the global context(GC) in the case of browsers. So when a global function(this is just a method nothing is there like a global function) is called the variable is just looked in the global context. And thus it'll identify the variable.
But if there is a function inside which an inner function is there then identifying a global variable will be two folds first it'll check in function scope and then in global scope. If the variable is a function variable. Then the variable will always be there in the functions execution context(EC)

Why do variables in the global scope get assigned to the window object?

var foo = 'bar';
console.log(window.foo); // bar
Seems like variables get assigned as properties to this, but inside anonymous functions, this refers to the parent scope, but doesn't assign variables to the parent scope.
function() {
var foo = 'bar';
}();
window.foo; // undefined
What object do variables get assigned to in non-global scopes?
To cite http://perfectionkills.com/understanding-delete/#execution_context:
Every execution context has a so-called Variable Object associated
with it. Similarly to execution context, Variable object is an
abstract entity, a mechanism to describe variable instantiation. Now,
the interesing part is that variables and functions declared in a
source text are actually added as properties of this Variable object.
When control enters execution context for Global code, a Global object
is used as a Variable object. This is precisely why variables or
functions declared globally become properties of a Global object
Yet, these Variable Objects are not accessible. The only non-internal one is the global object, window or this (in global context).
The relevant section in the specification is #10: Executable Code and Execution Contexts.
In JavaScript, all variables are assigned to some scope object. However, only the scope object of global variables is accessible in JavaScript in the browser through the window object. Variables in a function scope are assigned to some scope object used internally by the JavaScript runtime, but this cannot be accessed by the user.
In another environment, global variables may be accessible as properties of another object (such as GLOBAL in node.js) or may be inaccessible (such as application scripts running inside the Windows Script Host).
They're available only in the function they're declared in.
Function scope is the only other scope in JavaScript, btw, unlike block-scoping in other {} languages.)
Re: your edit Don't be fooled--JS's this semantics are a bit irksome IMO--this may not be what you expect under a variety of circumstances.
Inside self-invoking anonymous function eg:
function() {
....
}()
All variables remain inside it and do not attach themselves to global object or window. Using that technique, there are patterns created such as module/singleton pattern.
Notice that in JS, variables have function-level scope.

What does the global in (function(global){ some code .. })(this) do?

I was looking at adding comments to JSON and found this script that strips them out before processing making the JSON valid. I am just trying to understand how it works to make the JSON.minify() function available?
It starts with
(function(global){ ...
totally which is weird to me. I found that "global is a property of a RegExp instance, not the RegExp object" on MDN but I don't understand how it is works in this script if at all.
This snippet:
(function(global){
// your code here
// referring to the variable named "global" in this scope
// will be a reference to the default javascript global object
})(this);
is a construct for assigning the global object (whatever it might be) to an argument labeled global for all code that is inside this self-executing function.
The self executing function is used to define a separate execution scope so that any functions or variables you define inside this other scope will not interfere with or be directly accessible from outside this scope (insulating your scope from other code scopes).
In a browser, the global object is the window object, but if you intended to have code that might work in other javascript environments (like no node.js on a server) where the global object might not be window, this is a way of extracting the global value from the default this value, putting it into another variable which you can then refer to anywhere inside your code block.
For code mean to only run in a browser, there really is no point to this. You can just refer to window when you need the global object.
It's just a function parameter name. It might as well be froozboggles.
This code:
(function(foo) {
// In here, what's called "bar" in the outer scope is called "foo"
})(bar);
Defines an anonymous function taking one parameter bar and immediately calls it with the value of bar as the first parameter.
Apart from what jfriend00 mentions in his fine answer, it's also a good way of making sure that you don't leak variables and functions to the outer scope: If you declare, say, var baz = 17; in the top scope in javascript, it will be a property of window. If you wrap it in a function as in the pattern you mention, you can only export properties to window explicitly -- by assigning them to global, in the case of your example. Edit: As #josh3736 says in his comment, you can also leak to window by assigning without a previous declaration, e.g. quux = 4711;.

What does this block of JS code mean? [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the purpose of wrapping whole Javascript files in anonymous functions like “(function(){ … })()”?
I came across a JS file that can be summarized to the code below:
(function(window){
// some codes here
})(window);
I wonder what this block of code means? Has the window special meanings, or it is just a parameter? What are the differences between the two "window" we see in the brackets?
Since this function does not have a name, I assume it is an anonymous function, so is it only invoked once? When is it invoked?
This is called a immediately-invoked anonymous function. (IIAF for short.)
In this case, you are defining a function that takes in a parameter called "window" that overrides the global window object inside of that scope.
The kicker here is that right after defining the function, you're immediately invoking it, passing in the global window object, so it is as if you used the global reference within the function closure!
Most of the time, the purpose of this is to avoid polluting the global namespace by way of wrapping all potential variables within an anonymous scope.
As far your questions regarding window, the window in parentheses at the bottom is a reference to the global window object. The first window is just a name for a parameter. But in this instance it refers to the global window object since you're using an anonymous self-invoked function. You could call it monkeys and it wouldn't make a difference (of course, you'd have to use monkeys within the body of the anonymous function then, to refer to the parameter). So now, you now have a reference to the global window object within your function.
Yes, the function is invoked once and it is invoked as soon as it is defined. This is because it is a self-invoked anonymous function.
It's a closure. The code in question is a an anonymous function, which will execute with the "window" parameter (end of your snippet). It won't pollute the global namespace.
The first window is formal parameter, while the second one is actual parameter that actually invokes the function. This type of function called self-invoking functions.
The benefit of it is that wrapping functions this way doesn't clutter global scope..
It is an immediately invoked function expression. the grouping operator () around a function expression (essentially a function declaration without a name) means that the enclosed function is evaluated and a function object returned. A function followed by a formal parameter list (another set of ()) causes the function to be called, so:
(function() {
alert('hey');
})();
creates an anonymous function that is called immediately and run once. It doesn't create any global variables and leaves no trace of its existence.
Passing the indentifier window to the function means that it is passes whatever it references. The presumption here (I suppose) is that it will reference a global window object that, in browsers, is the global object. However, in an environment that doesn't have a global window object, it may well be undefined. It is a pointless exercise in my view.
If you are concerned about getting a refernce to the global object, then pass this from the global context:
(function(global) {
// global refernces the global object
})(this);

Categories