Scope of object properties & methods

In the article Show love to the object literal, it's said: When we have several scripts in a page, the global variables & functions will get overwritten if their name repeats.

One solution is to make the variables as properties & functions as methods of an object, and access them via the object name.

But will this prevent the issue of variables getting into the global namespace?

<script>
    var movie = {
        name: "a",
        trailer: function(){
           //code
        }
    };
</script>

In the above code which elements gets added to the global namespace? a) Just the object name - movie b) Object name as well as the properties and methods inside it – movie, movie.name, movie.trailer()

Answers


movie will exist in the global namespace (in a browser: window). Within the movie-scope exist: name and trailer. You can see this if you try executing trailer from the global object (window.trailer() will result in ReferenceError: trailer is not defined). trailer can only be executed using movie.trailer() (or window.movie.trailer()).

Javascript has lexical scope, aka static scope, meaning:

  • an identifier at a particular place in a program always refers to the same variable location — where “always” means “every time that the containing expression is executed”, and that

  • the variable location to which it refers can be determined by static examination of the source code context in which that identifier appears, without having to consider the flow of execution through the program as a whole 1.

1 Source


Need Your Help

Center a Div with dynamical height/width

html css center

i built a little site, in which I load content via ajax and jquery, when a link in my nav-section is clicked. The content is loaded into a div called "content". Now I want to center this div that

Understanding the concept of SpriteKit Nodes

xcode swift sprite-kit skspritenode skphysicsbody

So I'm very new to SpriteKit and Swift, and I don't really understand the concept behind nodes (or really anything in sprite-kit for the matter). I'm requesting you explain the concept of nodes to ...