本文詳細的介紹了JavaScript中的塊級作用域、私有變量與模塊模式,廢話就不多說了,具體如下:
1.塊級作用域(私有作用域),經常在全局作用域中被用在函數外部,從而限制向全局作用域中添加過多的變量和函數。
(function(count){
for(var i=0;i<count;i++){
console.log(i);//=>0、1、2、3、4
}
console.log(i);//=>5
})(5);
(function(){
var now=new Date();
if(now.getMonth()==0 && now.getDate()==1){
console.log("新年快樂");
}else{
console.log("盡情期待");
}
})();
2.私有變量:任何在函數中定義的變量,都可以認為是私有變量,因為不能在函數的外部訪問這些變量。
特權方法:有權訪問私有變量和私有函數的公有方法稱為特權方法。
2.1)在構造函數中定義特權方法:
function Person(name){
this.getName=function(){
return name;
};
this.setName=function(value){
name=value;
};
}
var person1=new Person("Jason");
console.log(person1.getName());//=>Jason
person1.setName("gray");
console.log(person1.getName());//=>gray
var person2=new Person("Michael");
console.log(person1.getName());//=>gray
console.log(person2.getName());//=>Michael
person2.setName('Alex');
console.log(person1.getName());//=>gray
console.log(person2.getName());//=>Alex
構造函數模式的缺點是針對每個實例都會創建同樣一組新方法。
2.2)靜態私有變量來實現特權方法
在私有作用域中,首先定義私有變量和私有函數,然後定義構造函數及其公有方法。
(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("Jason");
console.log(person1.getName());//=>Jason
person1.setName("gray");
console.log(person1.getName());//=>gray
var person2=new Person("Michael");
console.log(person1.getName());//=>Michael
console.log(person2.getName());//=>Michael
person2.setName('Alex');
console.log(person1.getName());//=>Alex
console.log(person2.getName());//=>Alex
3.模塊模式:通過為單例添加私有變量和特權方法能夠使其得到增強。
如果必須創建一個對象並以某些數據對其進行初始化,同時還要公開一些能夠訪問這些私有數據的方法,那麼就可以使用模塊模式。
var application=function(){
//私有變量和函數
var components=[];
//初始化
components.push(new BaseComponent());
//公共接口
return {
getComponentCount:function(){
return components.length;
},
registerComponent:function(){
if(typeof component=="object"){
components.push(component);
}
}
}
}();
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持。