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

javascript基础之九(JavaScript数据封装)

2015-10-27 14:23 483 查看
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript数据封装</title>
</head>
<script>
//简单的数据封装
function MyObject(){
var privateValue=0;//这里没有this
this.setValue=function(value){
privateValue=value;
};
this.getValue=function(){
return privateValue;
};
};
var obj=new MyObject();
console.info(obj.getValue(obj.setValue("100")));

//ECMA JavaScript定义属性
function Book(){
var name="";
Object.defineProperty(this,'name',{//这样与简单数据封装的效果相同
get:function(){
return name;
},  //定义了get,则属性可以被访问到
set:function(value){
name=value;
}//定义了set,属性才可被赋值
});//definepropert第一个参数为需要定义属性的对象,第二个为变量名,第三个为定义的属性,
};
var book=new Book();
book.name="java sc";
console.info(book.name);
//ECMA JavaScript标注的 对象工厂
var createPerson=function(firstName,lastName){
var person={};
Object.defineProperties(person,{
firstName:{
value:firstName,
writable:true,
emuerable:true,//可以在for循环中遍历
},
lastName:{
value:lastName,
writable:true,
emuerable:true,//可以在for循环中遍历
},
fullName:{
get:function(){
return this.firstName+" "+lastName;
},
emuerable:true,//可以在for循环中遍历
}
});
return person;
};
var person =createPerson("luo","sf");
console.info(person.fullName);

//应用实例
console.info("应用实例");
var Book=function(name,price){
var priceChanging=[];
var priceChanged=[];//这两个数组用于保存传入的回调函数

this.name=function(val){
if(val!==undefined){
name=val;
}
return name;//这返回的是闭包name中的当前值,不是对象中的函数
};
this.price=function(val){
if(val!==undefined && val!==price){
for(var i=0;i<priceChanging.length;i++){
if(!priceChanging[i](this,val)){
return price;
}
}
price=val;
for(var i=0;i<priceChanged.length;i++){
priceChanged[i](this);
}
}
return price;
}
this.onPriceChanging=function(callback){
priceChanging.push(callback);
}
this.onPriceChanged=function(callback){
priceChanged.push(callback);
}

};
var book=new Book("javascript",23.5);
console.info("name "+book.name());
console.info("price "+book.price());
book.onPriceChanging(function(b,price){
if(price<0){
console.log("price <0!");
return false;
}
return true;
});
book.onPriceChanged(function(b){
console.info("price changed :"+b.price());
});
book.price(-100);
book.price(10);
</script>
<body>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: