<<javascript the good parts>> variable scope

本文深入探讨了JavaScript中函数作用域的概念,解释了变量在函数内部的可见性和生命周期,并通过分析AngularJS源码展示了实际应用。重点讨论了如何在函数内声明变量以确保代码的清晰和高效,以及这种实践在大型框架如AngularJS中的体现。

Javascript does not have block scope, but it does have function scope. A variable defined anywhere within a function is visible everywhere within the function.

 

function foo(){
  console.log("a:",a);//variable a is visible here but it is still undefined
  console.log("f:",f);//variable f is visible here but it is still undefined
  var a=1;
  var f=function(){
    console.log("f");
  }
}

foo();

 

So, it is best to declare all of the variables used in a function at the top of the function body. If we check the angularjs source code, we find it does exactly the same way.

// at the top, it declares all the global variables
var $$scope           = '$scope',
    $boolean          = 'boolean',
    $console          = 'console',
    $length           = 'length',
    $name             = 'name',
    $object           = 'object',
...

// in each function, it also declare the variables at the top 
function forEach(obj, iterator, context) {
  var key;
  if (obj) {...
...
 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值