Javascript: is the Windows object a default object? - javascript

First time poster. I tried to search for answer before posting.
I'm new to javascript, coming from a Delphi/pascal background. I am used to things having to be explicitly spelled out. When I see code that includes setTimeout or setInterval (see here:
http://www.w3schools.com/js/tryit.asp?filename=tryjs_setinterval1), I notice that it just looks like an intrinsic function. But I think it is actually a method of the Windows object.
So it looks like the "window." part is optional. Is this somethign specific to the Window object? Or will any method that is specified without the name of it's containing object be recognized in javascript? And what would happen if there was another variable in the global scope that had a method also named setTimeout? How would the compiler/interpreter know which one to use?
Thanks so much,
Kevin

In Javascript, there is something called the Global scope. On Browsers, the global scope object is window. If you create a variable outside of a function, it goes by default into the global scope, which is window.
When invoking a method or referencing a variable on the window object, it's optional to include window.

its not windows its window (no 's' at end).
As far as i know javascript have 3 scopes local, [clouser], global
Every variable or function is first looked up in local scope, then clouser and finally if not found anywhere in between it will checked in global scope.
As in image you will see global scope is shown as Window object which mean whatever goes in global scope goes in window object.
copy paste below code in chrome devtools console
function outerFunction() {
var a = 10;
debugger;
function innerFunction() {
'use strict';
var b = 10;
debugger;
console.log(a);
}
innerFunction();
}
outerFunction();
on 1st debug
on 2nd debug

Related

Chrome console: difference between 'let' and 'var'?

I've attached an animated gif to illustrate this weird behavior. Essentially, my question is does Chrome console treat var and let differently when used in the same scope? You'll notice that after declaring / assigning a variable, if you try to type that variable's name into the console, Chrome will autocomplete it for you, showing a dropdown list containing what your typing. When using lets, this is not the case. Is this a bug, feature, or is there something I'm missing about var and let in JavaScript?
Note: I'm well aware that let lives & dies within the immediate scope.
When you use var in the console, it executes in the global scope and adds the variable to the window object.
When you use let in the console, it executes in the global scope, which doesn't add the variable to the window object.
When you start typing, autocomplete checks the parent object for properties to complete along with other language constructs, such as function, for, and while.
When there is no content in the console, the parent object is window, which won't have the property you're looking for because let doesn't add the property to window.
As soon as you have a new object for autocomplete to complete, behavior returns to what you'd expect.
> let foo = {bar: 'baz'};
> foo.b //autocompletes bar
Now, with all of that said, there's no reason that autocomplete has to behave that way. In many regards the lack of autocomplete for variables defined in global scope via let could be considered a "bug" worth "fixing". In my opinion it is moderately surprising behavior.
var defines a variable on the global scope, while let defines it only in the local scope. Most likely, the autocomplete is only looking on the global scope for targets.

Why JavaScript file starts with (function (undefined)? [duplicate]

Have you ever taken a look under the hood at the jQuery 1.4 source code and noticed how it's encapsulated in the following way:
(function( window, undefined ) {
//All the JQuery code here
...
})(window);
I've read an article on JavaScript Namespacing and another one called "An Important Pair of Parens," so I know some about what's going on here.
But I've never seen this particular syntax before. What is that undefined doing there? And why does window need to be passed and then appear at the end again?
The undefined is a normal variable and can be changed simply with undefined = "new value";. So jQuery creates a local "undefined" variable that is REALLY undefined.
The window variable is made local for performance reasons. Because when JavaScript looks up a variable, it first goes through the local variables until it finds the variable name. When it's not found, JavaScript goes through the next scope etc. until it filters through the global variables. So if the window variable is made local, JavaScript can look it up quicker.
Further information: Speed Up Your JavaScript - Nicholas C. Zakas
Undefined
By declaring undefined as an argument but never passing a value to it ensures that it is always undefined, as it is simply a variable in the global scope that can be overwritten. This makes a === undefined a safe alternative to typeof a == 'undefined', which saves a few characters. It also makes the code more minifier-friendly, as undefined can be shortened to u for example, saving a few more characters.
Window
Passing window as an argument keeps a copy in the local scope, which affects performance: http://jsperf.com/short-scope. All accesses to window will now have to travel one level less up the scope chain. As with undefined, a local copy again allows for more aggressive minification.
Sidenote:
Though this may not have been the intention of the jQuery developers, passing in window allows the library to be more easily integrated in server-side Javascript environments, for example node.js - where there is no global window object. In such a situation, only one line needs to be changed to replace the window object with another one. In the case of jQuery, a mock window object can be created and passed in for the purpose of HTML scraping (a library such as jsdom can do this).
Others have explained undefined. undefined is like a global variable that can be redefined to any value. This technique is to prevent all undefined checks from breaking if someone wrote say, undefined = 10 somewhere. An argument that is never passed is guaranteed to be real undefined irrespective of the value of the variable undefined.
The reason to pass window can be illustrated with the following example.
(function() {
console.log(window);
...
...
...
var window = 10;
})();
What does the console log? The value of window object right? Wrong! 10? Wrong! It logs undefined. Javascript interpreter (or JIT compiler) rewrites it this way -
(function() {
var window; //and every other var in this function
console.log(window);
...
...
...
window = 10;
})();
However, if you get the window variable as an argument, there is no var and hence no surprises.
I don't know if jQuery is doing it, but if you are redefining window local variable anywhere in your function for whatever reason, it is a good idea to borrow it from global scope.
window is passed in like that just in case someone decides to redefine the window object in IE, I assume the same for undefined, in case it's re-assigned in some way later.
The top window in that script is just naming the argument "window", an argument that's more local that the global window reference and it what the code inside this closure will use. The window at the end is actually specifying what to pass for the first argument, in this case the current meaning of window...the hope is you haven't screwed up window before that happens.
This may be easier to think of by showing the most typical case used in jQuery, plugin .noConflict() handling, so for the majority of code you can still use $, even if it means something other than jQuery outside this scope:
(function($) {
//inside here, $ == jQuery, it was passed as the first argument
})(jQuery);
Tested with 1000000 iterations. This kind of localization had no effect in performance. Not even a single millisecond in 1000000 iterations. This is simply useless.

Declare variable so that would be it visible in global context but not belong to window or gett

I need to emulate in firefox the behavior of activeXobject in last versions of ie. I write addon with contentScript and want to implement to pages such variable. It is exactly what I want - It is a challenge in itself.
Example of IE 11 working code:
if (window.ActiveXObject == undefined) {
var but = new window.ActiveXObject; // [ActiveXObject object]
}
I need exactly same behavior in firefox with my variable
For example what i want
<script>
console.log(window.variable) // undefined
console.log(new window.variable); // [object Variable]
console.log(new variable) // [object Variable] if not possible previous string
</script>
for solving, you can change the addon sdk or a browser source, change realization of all getters or something else
In browser Javascript, there is no such thing as a global variable that is not a property of the window object. So, if that's truly what you are trying to do, then it cannot be done. Yes, you might be able to create a getter on the window object with Object.defineProperty(), but that's still a property on the window object so I'm not sure how that helps you.
Likewise, there is no structure in Javascript such that:
window.ActiveXObject === undefined
and this works:
var x = new window.ActiveXObject;
Javascript just simply doesn't work that way. The property either exists or it doesn't. It can't be undefined for one way of accessing it and defined for some other way of accessing it.
You might also be able to create the property on the window object so it is not enumerable if you want it to be less visible for some reason.
If you explained what you're really trying to accomplish, there may be some work-arounds by enclosing the relevant code in a closure and defining the variable in the closure, but without knowing more details about what the actual problem to be solved is, we can't help more specifically than that.
If you just want the variable defined for YOUR code only, then you can just put it in a closure:
(function() {
var myVar = "foo";
// other parts of your code
// elsewhere in your code
console.log(myVar);
})();
Your code can treat it like a global, but it's really not a global, it's just defined within the scope that your code lives and not available to any other code outside this scope.
Theoretically, this is possible with lexically declared variables in ES6:
let variable = 5;
console.log(variable); // 5
console.log(window.variable) // undefined
However, the current let support in FF is not as advanced, and still treats this a property of the global object.
If the variable only needs to be accessible by your project code, wrap all of your project code in a self executing anonymous function.
(function(){
var internalGlobalVar = "some value";
//All your code gets wrapped in here...
})();
Then if you tried to alert(window.internalGlobalVar) you would get undefined.
We use google closure compiler with plovr and wrap all of our code in a self executing anonymous function so basically all of our global variables are project scope, not on the window "output-wrapper": "(function($){%output%})(jQuery);"

Javascript function implementation

I have code like this :
(function() {
$(document).ready(function() {
//event handlers
$('.project-delete').on('click', function() {
deleteProject($(this));
});
$('.keyword-delete').on('click', function() {
deleteKeyword($(this));
});
this.deleteKeyword = function(model) {
}
}).call(this);
I am curious if this is a good approach since I was learning JS recently and as far as I understand this function will have global scope, doesn't it ? since .call(this) is passing window object to this closure then I think it is not the best option ? Is there something I am missing ? Does changing .call(this) to just () change anything ?
EDIT:So is it OK to just pass window object to that closure ? Wouldn't it better to pass just a empty object or jQuery object ?
Assuming this function is defined in the global scope, the deleteKeyword function will have also have global scope since this in the context of the parent function is basically window (which has been passed in as this from outside; in the global scope this === window).
If you change .call(this) to just (), this is still window inside the function. This is because when you call a function via a simple function-call, this is set to the global object, which is window.
If you want a different value for this, you will need to pass in something else via .call or .apply.
For more information about the behavior of this, take a look here.
"as far as I understand this function will have global scope, doesn't it?"
"Scope" is about what variables a function has access to (i.e., its own local variables, plus locals declared in any functions that it might be nested inside, plus global variables), and that has nothing to do with the value of this. Scope depends on where the function declaration is, but this depends on how the function is called.
"since .call(this) is passing window object to this closure"
We can't tell that just from the code shown. Presumably you mean that that block of code is not nested inside some other function, so then yes, this would be window. But if that code was ever pasted inside some other function then that this might have some other value depending on how that other function was called.
"Does changing .call(this) to just () change anything?"
If you use just () that will mean that inside the function this will be window. Whether that changes anything depends on whether the this in .call(this) was window in the first place - as I already mentioned above, if that block were nested inside some other function this could be something else. Having said that, for the code shown if this was anything other than window I think your code would break. Because you declare a function like this:
this.deleteKeyword = function(model) {...}
...and then inside the second click handler you call what I assume is meant to be the same function without using this:
deleteKeyword($(this));
The only way that will work is if this is window and the deleteKeyword() function is thus global. If this were any other object the function would be a property of that other object and thus not accessible directly as deleteKeyword(). But unless you specifically want deleteKeyword() to be accessible from other code not shown there is no reason to create it as a property of this at all. Just declare it with var:
var deleteKeyword = function(...
...and then it will be accessible only inside that function and the ones nested in it such as your click handler. And the .call() at the end of your function would be redundant since the function wouldn't ever actually use this.
"so isn't it a better option to apply jQuery object (or maybe just empty object) to it to increase performance? Wouldn't it increase performance if this would point to local scope? Since window object is very slow."
Well as I already said, "scope" and the value of this are unrelated concepts. I'm not sure why you are worrying about performance for that code. But if you were to apply jQuery or an empty object with .call(jQuery) or .call({}) the code would not work as explained above.

JavaScript variable scope question: to var, or not to var

Many thanks in advance. I'm working out of a schoolbook and they're using one function to call another which opens a window:
function rtest(){
content='dans window';
oneWindow=open("","Window 1","width=450,height=290");
newWindow(oneWindow);
}
function newWindow(x){
x.document.close();
x.document.open();
x.document.write(content);
x.document.close();
x.moveTo(20,20);
x.focus();
}
So everything works fine, but my question is this: how is the newWindow() function able to access the contents of the "contents" variable in the rtest() function? And why, if I preface the "content" variable with "var", like this:
function rtest(){
**var content='dans window';**
oneWindow=open("","OneWindow","width=450,height=290");
newWindow(oneWindow);
}
...does an error get thrown (and the contents of the new window left blank)?
Can anybody explain to me what the difference between using var and not using var is?
Thank you!
Daniel
if you dont use var inside the rtest, it is automatically a global variable. which is why it is accessible from other javascript codes including newWindow. now, when you use var, it automatically a variable inside the rtest scope, so the ones that can use it now are those inside the same scope.
If you declare the variable using var inside the original function, it will become a local variable and will not be visible outside the function.
If you don't declare the variable at all, it will be global. However, best practice is to declare global variables. If your textbook doesn't do this, consider replacing it. If your professor doesn't do this, consider replacing (or reforming) him. :-) If you have trouble convincing him, you can (but not necessarily should) mention that I'm one of the top 200 users here.
For example:
var content;
function rtest(){
content='dans window';
oneWindow=open("","Window 1","width=450,height=290");
newWindow(oneWindow);
}
Also, the best way to open a blank window is to call open("about:blank", ...), not open("", ...).
It's about the function-scope, if you declare your variable with var, it will be available only in the scope of the function where you did it.
If you don't use the var statement, and you make an assignment to an undeclared identifier (an undeclared assignment), the variable will be added as a property of the Global object.
If you don't use var, then you are creating a global variable; that is, a variable that is accessible from any code anywhere in your program. If you use var, you are creating a local variable, which is a variable that is only accessible from within the scope in which it is defined (generally, the function it is defined in).
While global variables can be convenient at first, it's generally a bad idea to use them. The problem is that all of your code will share that one global variable; in the future, if you need to have two or more different versions of that variable for whatever reason, you won't be able to separate the two uses. Global variables can also be accessed or changed from anywhere within your program, so it can be hard to figure out what might be modifying or depending on one, while local variables can only be accessed within a limited, well defined section in code, which can easily be inspected.
With var you declare a local variable in the function which is thus not visible outside this function. Without var you are actually working on the window object and set or overwrite a field of it. Your global scope in client side Javascript is always the window object. So you could also have written window.content='dans window'; to make clearer what you are actually doing there, but otherwise it would be identical. By the way: the window variable is itself just a field of the window object that refers recursively back to the window.

Categories

Resources