1對象定義
/**
* javascript 對象的創建於應用
*/
//創建一個簡單的json對象 具體的一個實例
var user={"name":"jyf","age":18,"place":"shanghai"}
//添加一個屬性 sex
user.sex="Man"
//修改屬性
user.age=23
//刪除屬性
delete user.place
console.info(user)
2 類的創建
//創建一個類
/**
* 定義一個類 Computer 電腦類
* 有公開屬性 place, type
* 私有屬性 price
* 獲取價格方法 getPrice setPrice
*/
var Compurter=function(place,type){
this.place=place
this.type=type
_price=4500
this.setPrice=function(price){
_price=price
}
this.getPrice=function(){
return _price
}
}
//擴展一個屬性 name
Compurter.prototype.name
Compurter.prototype={
//原型對象默認是指向Compurter,所以擴展原型對象首先需要指定constructor:Compurter
constructor:Compurter,
//擴展原型屬性
id:18,
getComputer:function(){
//這裏需要使用this指向當前對象,否則會去windows對象的相關屬性
return this.id+':'+this.place+':'+this.name;
}
}
//實例化一個對象,需要注意的是:擴展屬性必須放在實例化之前,否則有undefined的報錯
var lenovo=new Compurter("北京","聯想")
lenovo.name='abc'
console.info(lenovo.getComputer());
3 單體模式(單例)
//對象的單體模式
var Box={};
Box.Array={
each:function(){
alert("each")
},
filter:function(){
alert("filter")
}
}
Box.toMethod=function(){
alert("Method")
}
Box.Array.each()
Box.Array.filter()
Box.toMethod();
//閉包單體
var Bag=(function(){
var w=50;
var h=80;
var l=100;
return {
cal:function(){
return w*l*h;
}
}
})();
console.info(Bag.cal());