您的位置:首页 > Web前端 > JavaScript

[JavaScript] 模拟块级作用域、私有变量/函数

2013-05-10 11:54 639 查看
JavaScript没有块级作用域的概念。

function outputNumbers(count){
for (var i=0; i < count; i++){
alert(i);
}
alert(i);   //计数
}


  ①块语句中定义的变量,实际是在包含函数中而非语句中创建的。即变量i的作用域是它的包含函数outputNumber(),而不是for语句。
    在java、C++等语言中,变量i只会在for语句块中定义,循环结束后就被销毁。
  ②甚至在outputNumber()函数中可以重新声明同一个变量,JavaScript会忽略后续的声明但会执行声明中的初始化

静态私有变量

(function(){

var name = "";

Person = function(value){
name = value;
};

Person.prototype.getName = function(){
return name;
};

Person.prototype.setName = function (value){
name = value;
};
})();

var person1 = new Person("Nicholas");
alert(person1.getName());   //"Nicholas"
person1.setName("Greg");
alert(person1.getName());   //"Greg"

var person2 = new Person("Michael");
alert(person1.getName());   //"Michael"
alert(person2.getName());   //"Michael"
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: