Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: global scope

Nowdays, i create a .js file with a lot of functions and then I link it to my html pages. That's working but I want to know what's the best way (good practices) to insert js in my pages and avoid conflicts with scope... Thank you.

like image 247
thomas Avatar asked Jul 16 '10 14:07

thomas


People also ask

What is the global scope in JavaScript?

In a programming environment, the global scope is the scope that contains, and is visible in, all other scopes. In client-side JavaScript, the global scope is generally the web page inside which all the code is being executed.

What is global scope and local scope in JavaScript?

Scope in JavaScript refers to the current context of code, which determines the accessibility of variables to JavaScript. The two types of scope are local and global: Global variables are those declared outside of a block. Local variables are those declared inside of a block.

Is let global scope JavaScript?

let allows you to declare variables that are limited to the scope of a block statement, or expression on which it is used, unlike the var keyword, which declares a variable globally, or locally to an entire function regardless of block scope.

What are the three types of scopes in JavaScript?

JavaScript has 3 types of scope: Block scope. Function scope. Global scope.


2 Answers

You could wrap them in an anonymous function like:

(function(){ /* */ })();

However, if you need to re-use all of the javascript functions you've written elsewhere (in other scripts), you're better off creating a single global object on which they can be accessed. Either like:

var mySingleGlobalObject={};
mySingleGlobalObject.someVariable='a string value';
mySingleGlobalObject.someMethod=function(par1, par2){ /* */ };

or the alternative, shorter syntax (which does the same thing):

var mySingleGlobalObject={
  someVariable:'a string value',
  someMethod:function(par1, par2){ /* */ }
};

This can then be accessed later from other scripts like:

mySingleGlobalObject.someMethod('jack', 'jill');
like image 198
lucideer Avatar answered Sep 25 '22 07:09

lucideer


A simple idea is to use one object that represents your namespace:

var NameSpace = {
    Person : function(name, age) {

    }
};

var jim= new NameSpace.Person("Jim", 30);
like image 26
ChaosPandion Avatar answered Sep 22 '22 07:09

ChaosPandion