首页 > 其他 > 详细

变量的作用域

时间:2016-12-19 14:39:11      阅读:157      评论:0      收藏:0      [点我收藏+]
A globally-scoped variable

var a = 1;

// 全局变量
function one() {
  alert(a); // alerts ‘1‘
}

局部变量

var a = 1;

function two(a) {
  alert(a); // alert出 形参 a 的 实参,而不是全局变量 a 的值‘1‘
}

// 本地变量
function three() {
  var a = 3;
  alert(a); // alerts  本地的  a 的值‘3‘
}

Intermediate: JavaScript 没有类似的块级作用域(ES5; ES6 引入 let)

var a = 1;

function four() {
  if (true) {
    var a = 4;
  }

  alert(a); // alerts ‘4‘, 而不是全局变量 a 的值 ‘1‘
}

Intermediate: Object properties
对象的属性--
var a = 1;

function five() {
  this.a = 5;
}

alert(new five().a); // alerts ‘5‘

Advanced: Closure

var a = 1;

var six = (function() {
  var a = 6;

  return function() {
    // JavaScript "closure" means I have access to ‘a‘ in here,
    // because it is defined in the function in which I was defined.
    //闭包访问上级函数中的变量,
    alert(a); // alerts ‘6‘
  };
})();

Advanced: Prototype-based scope resolution
基于原型的作用域
http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript
--这个没法写了,出处如上,但感觉这个基于原型的案例看着很别扭,、
就实践了一下,果然有问题。

 

变量的作用域

原文:http://www.cnblogs.com/funnyweb/p/6197075.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!