本文转载自:http://blog.csdn.net/zjwtnt/archive/2010/08/02/5782387.aspx
原作者:.Kaway.Cheng
/*oop中的封装在javascript中的应用
man
构造方式 var 变量名 = new man(参数1,参数2,参数3)
*/
var man = function(){
var paramsLength = arguments.length;/*可变参数长度*/
var name = "张三";/*默认nane值*/
var age = 25; /*默认age值*/
var business = "web bulider";/*默认职业值*/
/*处理参数*/
if(paramsLength==3){
name = arguments[0];
age = arguments[1];
business = arguments[2];
}
/*获得name方法*/
this.getname = function(){
return name;
};
/*name赋值方法*/
this.setname = function(mingzi){
name = mingzi;
};
/*获得age方法*/
this.getage = function(){
return age;
};
/*age赋值方法*/
this.setage= function(nianling){
age = nianling;
};
/*获得business方法*/
this.getbusiness = function(){
return business;
};
/*business赋值方法*/
this.setbusiness= function(zhiye){
business = zhiye;
};
/*返回内容*/
this.stringMe = function(){
return "姓名为"+name+",他的年龄为"+age+",职业是"+business;
}
}
/*实例化*/
var me = new man("tomie",25,"打酱油的");
alert(me.stringMe());
me.setname("李四");
me.setage(1000);
me.setbusiness("做俯卧撑的");
alert(me.stringMe());
/*oop中的继承在javascript中的应用
man类为本演示的基本类
具有姓名、年龄、职业三个属性
*/
var man = function(){
/*定义私有变量*/
var name = "张三";/*默认nane值*/
var age = 25; /*默认age值*/
var business = "web bulider";/*默认职业值*/
/*获得name方法*/
this.getname = function(){
return name;
};
/*name赋值方法*/
this.setname = function(mingzi){
name = mingzi;
};
/*获得age方法*/
this.getage = function(){
return age;
};
/*age赋值方法*/
this.setage= function(nianling){
age = nianling;
};
/*获得business方法*/
this.getbusiness = function(){
return business;
};
/*business赋值方法*/
this.setbusiness= function(zhiye){
business = zhiye;
};
}
/*
manjob类,本演示的子类
将继承基类的性质
*/
var manjob = function(){
/*定义私有变量*/
var page = "3个";/*做了多少个页面*/
var js = "10个"; /*做了多少个JS*/
var flash = "100个";/*做了多少个flash*/
var feel = "bad"; /*感觉如何*/
/*获得page方法*/
this.getpage = function(){
return page;
};
/*page赋值方法*/
this.setpage = function(yemian){
page = yemian;
};
/*获得js方法*/
this.getjs = function(){
return js;
};
/*js赋值方法*/
this.setjs = function(jiaoben){
js = jiaoben;
};
/*获得flash方法*/
this.getflash = function(){
return flash;
};
/*flash赋值方法*/
this.setflash = function(donghua){
flash = donghua;
};
/*获得feel方法*/
this.getfeel = function(){
return "心情很"+feel;
};
/*feel赋值方法*/
this.setfeel = function(xinqing){
feel = xinqing;
};
}
/*
继承开始,用manjob的prototype方式呼叫
man类,继承man类的属性和方法
*/
manjob.prototype = new man();
/*实例化*/
var mydate = new Date();
var tomie = new manjob();//实例化一个manjob
/*赋值*/
tomie.setname("tomie");/*基类*/
tomie.setage(25);/*基类*/
tomie.setbusiness("前端开发");/*基类*/
tomie.setpage("20个");/*子类*/
tomie.setjs("200个");/*子类*/
tomie.setflash("10个");/*子类*/
tomie.setfeel("happy");/*子类*/
/*打印结果*/
alert("继承后返回的方法为:"+tomie.getname + tomie.getage + tomie.getbusiness +
tomie.getpage + tomie.getjs + tomie.getflash + tomie.getfeel)
alert(tomie.getname() +"年龄为"+ tomie.getage() +"岁,职业为"+
tomie.getbusiness() +",于"+(mydate.getMonth()+1)+"月完成了页面"+
tomie.getpage() +",脚本"+ tomie.getjs() +",动画"+ tomie.getflash() +","+
tomie.getfeel())