Ways to break JavaScript Scope

JavaScript normally follows the function scope ie variables are accessible only within the function in which they are declared.

One of the ways to break this convention and make the variable accessible outside the function scope is to use the global window object eg

window.myVar = 123;

My question is are there any other ways in JavaScript/jQuery to make the variable accessible outside the function scope?


Not with variable declarations, no. You can obviously declare a variable in an outer scope so that it's accessible to all descendant scopes:

var a; // Available globally
function example() {
    a = "hello"; // References a in outer scope
}

If you're not in strict mode you can simply remove the var keyword. This is equivalent to your example:

// a has not been declared in an ancestor scope
function example() {
    a = "hello"; // a is now a property of the global object
}

But this is very bad practice . It will throw a reference error if the function runs in strict mode:

function example() {
    "use strict";
    a = "hello"; // ReferenceError: a is not defined
}

As you wrote, variables are only visible inside the function in which they were defined (unless they are global).

What you can do is assign variables to the function object itself:

function foo() {
    foo.myVar = 42;
}

console.log(foo.myVar); // outputs "undefined"
foo();
console.log(foo.myVar); // outputs "42"

But I would advise against it. You should really have a very good reason to do something like this.


You can define them as part of a global object, then add variables later

// Define your global object
var myObj = {};
// Add property (variable) to it
myObj.myVar = 'Hello world';
// Add method to it
myObj.myFunctions = function() {
    // Do cool stuff
};

See the link below:

Variable declaration

Also, you can declare it without the var keyword. However, this may not be a good practice as it pollutes the global namespace. (Make sure strict mode is not on).

Edit: I didn't see the other comments before posting. @JamesAllardice answer is also good.

链接地址: http://www.djcxy.com/p/97002.html

上一篇: ES6类使用bind vs call调用类中的方法?

下一篇: 如何打破JavaScript范围