config对象

时间:2025-04-23 13:34:08

在js中经常定义一个config对象来保存当前对象里面的一些临时变量;定义这个变量可以被对象中所有的属性访问到,可以避免重复,减少内存占用,统一管理;

如:

 <script>
function dateFormat(date,format){
var o = {
"M+" : date.getMonth()+1, //month
"d+" : date.getDate(), //day
"h+" : date.getHours(), //hour
"m+" : date.getMinutes(), //minute
"s+" : date.getSeconds(), //second
"q+" : Math.floor((date.getMonth()+3)/3), //quarter
"S" : date.getMilliseconds() //millisecond
}
if(/(y+)/.test(format)) format=format.replace(RegExp.$1,
(date.getFullYear()+"").substr(4- RegExp.$1.length));
for(var k in o)if(new RegExp("("+ k +")").test(format))
format = format.replace(RegExp.$1,
RegExp.$1.length==1? o[k] :
("00"+ o[k]).substr((""+ o[k]).length));
return format;
} //产品对象
/*对象内如何使用对象的属性和方法:this,对象外如何使用:先实例化,后用点语法*/
/*类 -- 抽象对象*/
function Product(name,price) {
/*属性 行为 可以为空或者给默认值*/
this.name=name
this.price=1000;
this.description = '';
this.zhekou = ''
this.sales = ''
this.produceDate
/*我们的需求:自动计算打折后的价格*/
Object.defineProperty(this, "price", {
value:5000000,
writable: false,
});
Object.defineProperty(this, "produceDate", {
get: function () {
return dateFormat(produceDate,'yyyy年MM月dd日');
},
set: function (value) {
produceDate = value;
}
});
var that = this;
//定义一个变量 :这个变量可以被对象中所有的属性访问到。。。。
/*避免重复,减少内存*/
/*统一管理*/
this.config = {
btnConfirm: document.getElementById('btn'),
btnBuy: document.getElementById('btn'),
btnAddCart: document.getElementById('btn'),
domProductName : document.getElementById('pname'),
domProductPrice : document.getElementById('pprice'),
sum : 1000,
des : document.getElementById('pdes'),
youhuijia : document.getElementById('pyouhui'),
zhekou : document.getElementById('pzhekou'),
sales : document.getElementById('psales'),
date : document.getElementById('date')
}
function bindDOM(){
/*绑定元素*/
/*通过点语法访问对象中的属性或者方法*/
that.config.name.innerHTML=that.name
that.config.price.innerHTML=that.price
that.config.des.innerHTML=that.description
that.config.youhuijia.innerHTML=that.youhuijia
that.config.zhekou.innerHTML=that.zhekou
that.config.sales.innerHTML=that.sales
that.config.date.innerHTML=that.produceDate
}
function bindEvents(){
/*绑定事件*/
that.config.btn.onclick = function(){
that.addToCart()
}
}
this.init = function(){
bindDOM()
bindEvents()
}
} //定义对象的两种方式
Product.prototype={ getPrice:function() {
return this.price
},
addToCart:function(){
alert('将物品添加到购物车')
}
} Product.prototype.buy=function(){
}
Product.prototype.addToCart=function(){ } /*搭积木开发 -- 代码可读性极高*/
window.onload=function() { /*实例化 -- 实例 -- 具体*/
//如何使用
//对象的使用必须先实例化,对象定义好之后,都是抽象的,必须实例化成具体
var iphone = new Product()
/*给对象的赋值赋值,也可以新增属性*/
iphone.name='iphone7'
iphone.price=6000
iphone.description='手机中的战斗机'
iphone.youhuijia=3000
iphone.zhekou=3.0
iphone.sales=40000
iphone.produceDate=new Date()
/*无法使用私有成员*/
// iphone.bindDOM()
// iphone.bindEvents()
/*只能使用共有成员*/
iphone.init()
} </script>