[翻译]Scope in JavaScript

Daily Tips原文地址(翻译练手文章篇幅不大,1到2分钟。)javascript

2017年12月13日java

JavaScript的做用域(Scope in JavaScript)

做用域是使用变量或者函数的上下文。有三种类型的做用域:全局做用域、局部做用域和词法做用域。(Scope is the context in which a function or variable is accessible. There are three types of scope: global, local, and lexical.)bash

高层次来讲,函数能使用定义在他们自己以外的变量和其余函数。(At a high level, functions have access to variables and other functions set outside themselves, but not variables set inside other functions.)ide

全局变量(Global Scope)

在其余的函数中均可以使用定义在全局做用域中的变量和函数(A variable or function in the global scope is accessible inside other functions.)函数

// this is in the global scope(这是在全局做用域中)
var sandwich = 'tuna';

var logSandwich = function () {
    // Will log `tuna` in the console(将会打印tuna)
    // It can access sandwich because it`s in the global scope(能够使用sandwich,由于它在全局做用域中)
    console.log(sandwich);
};
logSandwich();

// Will also log `tuna` in the console(一样会打印tuna)
console.log(sandwich);
复制代码

局部做用域(Local Scope)

变量或者函数只能被你代码自己所在的局部做用域中使用(A variable or function that’s only accessible in a part of your code base has local scope.)ui

var logSandwich = function () {
    // this has variable local scope(这是局部做用域)
    var sandwich = 'tuna';

    // Will log `tuna` in the console(将会打印tuna)
    // It can access sandwich because it`s scope is local to the function(能够使用sandwich,由于它处于函数自己的局部做用域)
    console.log(sandwich);
};
logSandwich();

// returns "Uncaught ReferenceError: sandwich is not defined"(返回‘Uncaught ReferenceError: sandwich is not defined’)
// `sandwich` is local to the logSandwich() function, and not accessible here(sandwich是logSandwich函数的局部变量,在这里不能使用)
console.log(sandwich);
复制代码

词法做用域(Lexical Scope)

若是你把你的函数,变量和其余一些函数藏在父类函数里面定义就会产生词法做用域,而且能被定义在其中的嵌套函数使用。父类函数不能使用定义在其中的嵌套函数里的变量及其方法。(If you nest your functions, variables and other functions defined in the parent function have lexical scope and can be accessed by the inner funtions. The parent function cannot access variables or functions defined within the inner functions.)this

var sandwiches = function () {

    // this is in the lexical scope(这是词法做用域)
    var sandwich = 'tuna';

    var logSandwich = function () {

        // Will log `tuna` in the console(将会打印tuna)
        // It can access sandwich because it's in the lexical scope(能使用sandwich,由于他在词法做用域中) console.log(sandwich); // Will log `chips` because it's in the local scope(将会打印chips由于在局部做用域中)
        var snack = 'chips';
        console.log(snack);

    };
    logSandwich();

    // Will also log `tuna` in the console(将会打印tuna)
    console.log(sandwich);

    // returns "Uncaught ReferenceError: snack is not defined"(返回‘Uncaught ReferenceError: snack is not defined’)
    // `snack` is local to the logSandwich() function, and out of the lexical scope(snack在logSandwich()函数中处于局部做用域,在这儿处于词法做用域)
    console.log(snack);

};
sandwiches();
复制代码

完!spa

相关文章
相关标签/搜索