Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What do window objects (window.something = something) do in JavaScript?

Tags:

javascript

I don't know if you need to see the full code, but I have seen a few plugins that do this:

window.dataValidate = dataValidate

Does this add 'dataValidate' to the window object, or how does it work?

like image 399
Stephen Jenkins Avatar asked May 25 '13 10:05

Stephen Jenkins


People also ask

What is the use of window object in JavaScript?

The Window Object It represents the browser's window. All global JavaScript objects, functions, and variables automatically become members of the window object. Global variables are properties of the window object. Global functions are methods of the window object.

What does window object do?

The window object represents an open window in a browser. If a document contain frames (<iframe> tags), the browser creates one window object for the HTML document, and one additional window object for each frame.

What is the difference between window and object in JavaScript?

The window object represents a window in browser. An object of window is created automatically by the browser. Window is the object of browser, it is not the object of javascript. The javascript objects are string, array, date etc.

What does window mean in JavaScript?

A global variable, window , representing the window in which the script is running, is exposed to JavaScript code. The Window interface is home to a variety of functions, namespaces, objects, and constructors which are not necessarily directly associated with the concept of a user interface window.


1 Answers

Does this add 'dataValidate' to the window object

Yes, it will.

For example, if you're inside another scope;

function foo() {
    var bar = 4;

    window.bar = bar;
}

You've now made bar global, and can access it from anywhere. Without the window.bar = bar, you'd only have been able to access it within foo().

You'll commonly see this being used at the end of an IIFE, to publish work to the rest of the world (e.g. jQuery);

(function () {
   var jQuery;

   // Setup jQuery

   window.jQuery = jQuery;
}());

You might see people doing this instead;

function foo() {
    bar = 4; // Note the lack of `var`
}

This has the same effect through the use of "implied globals"; but it will throw an error in ES5 strict mode, and is generally considered a bad practice (did the programmer mean to make it global, or did they simply accidentally omit var?).

like image 79
Matt Avatar answered Oct 24 '22 00:10

Matt