Daily Tips原文地址(翻譯練手文章篇幅不大,1到2分鐘。)javascript
2017年12月13日java
做用域是使用變量或者函數的上下文。有三種類型的做用域:全局做用域、局部做用域和詞法做用域。(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
在其餘的函數中均可以使用定義在全局做用域中的變量和函數(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);
複製代碼
變量或者函數只能被你代碼自己所在的局部做用域中使用(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);
複製代碼
若是你把你的函數,變量和其餘一些函數藏在父類函數裏面定義就會產生詞法做用域,而且能被定義在其中的嵌套函數使用。父類函數不能使用定義在其中的嵌套函數裏的變量及其方法。(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