日期:2014-05-16  浏览次数:20367 次

JS类的建立和使用
//类的建立和使用例子一
document.write("<strong>类的建立和使用例子一</strong><br>");
function Person (myName,myAge) {
//创建类的属性age,nickName
this.age = myAge;
this.nickName = myName;
//创建类的方法showInfo
this.showInfo= function () {
return(" hi ! my name is "+this.nickName+", I am "+this.age);
}
}

var tom = new Person("Tom",10);//创建类的实例
var info = tom.showInfo();//调用方法,将结果存到变量info里面
document.write(info+"<br>");//写出这个变量
document.write(tom.nickName+"<br>");//写出tom的nickName参数值
document.write(tom.age+"<br>");//写出tom的age参数值

//类的建立和使用例子二
document.write("<strong>类的建立和使用例子二</strong><br>");
function Person2 () {
//创建类的属性
this.age2;
this.nickName2;
//创建类的方法
this.showInfo2= function () {
return(" 你好,我的名字是 "+this.nickName2+", 我"+this.age2+"岁了。");
}
}

var tom2 = new Person2();//创建类的实例
tom2.age2 = 27;
tom2.nickName2 = "azhou";
var info2 = tom2.showInfo2();//调用方法,将结果存到变量里面
document.write(info2+"<br>");//写出这个变量
document.write(tom2.nickName2+"<br>");//写出实例的属性参数值
document.write(tom2.age2+"<br>");//写出实例的属性参数值

//使用prototype定义方法和属性1
document.write("<strong>使用prototype定义方法和属性</strong><br>");
function Mlist (Myname,Mytime) {
//使用prototype定义属性,this.myname同等与Mlist.prototype.myname,使用该属性无需实例化,只需使用类引用该属性
Mlist.prototype.myname = Myname;
Mlist.prototype.mytime =Mytime;
//类名称.prototype.方法名称=function{}使用prototype定义方法的语法格式,和this效果一样
Mlist.prototype.method_name = function() {
return(Mlist.myname+"与"+Mlist.mytime+"年参加了工作。")
};
};
Mlist.myname ="azhou";
Mlist.mytime =2007;
document.write("使用类直接调用Mlist.myname属性是:"+Mlist.myname+"<BR>");
document.write("使用类直接调用属性Mlist.mytime是:"+Mlist.mytime+"<BR>");
var mymlist_1 =new Mlist("azhou",2007);
document.write(mymlist_1.method_name()+"<BR>");
document.write("使用实例调用属性:"+mymlist_1.myname+"<BR>");
document.write("使用实例调用属性:"+mymlist_1.mytime+"<BR>");