Anish
Anish

Reputation: 1164

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()

Upvotes: 2

Views: 2857

Answers (1)

KooiInc
KooiInc

Reputation: 122956

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

Upvotes: 3

Related Questions