深入理解Javacript从作用域作用域链开始

   640?wx_fmt=gif

 
 

1. 什么是作用域

作用域是你的代码在运行时,某些特定部分中的变量,函数和对象的可访问性。换句话说,作用域决定了变量与函数的可访问范围,即作用域控制着变量与函数的可见性和生命周期

2. JavaScript中的作用域

在 JavaScript 中有两种作用域

如果一个变量在函数外面或者大括号{}外声明,那么就定义了一个全局作用域,在ES6之前局部作用域只包含了函数作用域,ES6为我们提供的块级作用域,也属于局部作用域

2.1 全局作用域

拥有全局作用域的对象可以在代码的任何地方访问到, 在js中一般有以下几种情形拥有全局作用域:

  1. 最外层的函数以及最外层变量:

var globleVariable= 'global';  // 最外层变量function globalFunc(){         // 最外层函数    var childVariable = 'global_child';  //函数内变量    function childFunc(){        // 内层函数        console.log(childVariable);    }    console.log(globleVariable)}console.log(globleVariable);  // globalglobalFunc();                 // globalconsole.log(childVariable)   // childVariable is not definedconsole.log(childFunc)       // childFunc is not defined'global';  // 最外层变量
function globalFunc(){ // 最外层函数
var childVariable = 'global_child'; //函数内变量
function childFunc(){ // 内层函数
console.log(childVariable);
}
console.log(globleVariable)
}
console.log(globleVariable); // global
globalFunc(); // global
console.log(childVariable) // childVariable is not defined
console.log(childFunc) // childFunc is not defined

从上面代码中可以看到globleVariableglobalFunc在任何地方都可以访问到, 反之不具有全局作用域特性的变量只能在其作用域内使用。

  1. 未定义直接赋值的变量(由于变量提升使之成为全局变量)

function func1(){    special = 'special_variable';    var normal = 'normal_variable';}func1();console.log(special);    //special_variableconsole.log(normal)     // normal is not defined
special = 'special_variable';
var normal = 'normal_variable';
}
func1();
console.log(special); //special_variable
console.log(normal) // normal is not defined

虽然我们可以在全局作用域中声明函数以及变量, 使之成为全局变量, 但是不建议这么做,因为这可能会和其他的变量名冲突,一方面如果我们再使用const或者let声明变量, 当命名发生冲突时会报错。

// 变量冲突var globleVariable = "person";let globleVariable = "animal"; // Error, thing has already been declared
var globleVariable = "person";
let globleVariable = "animal"; // Error, thing has already been declared

另一方面如果你使用var申明变量,第二个申明的同样的变量将覆盖前面的,这样会使你的代码很难调试。

var name = 'koala'var name = 'xiaoxiao'console.log(name);  // xiaoxiao'koala'
var name = 'xiaoxiao'
console.log(name); // xiaoxiao

2.2 局部作用域

和全局作用于相反,局部作用域一般只能在固定代码片段内可以访问到。最常见的就是函数作用域

2.2.1 函数作用域
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值