1、構造函數方式
用構造函數模擬"類",在其內部用this關鍵字指代實例對象。
基本語法:
function 類名(){
this.屬性名;//公共屬性
var 屬性名;//私有屬性
/*凡是定義類的公共屬性和公共方法都要使用this*/
//定義類的公共函數
this.函數名=function(){
.....
}
//定義類的私有函數
function 函數名(){
......
}
}
例子:
/*定義一個Person類*/
function Person(_name, _age, _salary) {
//Person類的公開屬性,類的公開屬性的定義方式是:”this.屬性名“
this.name = _name;
//Person類的私有屬性,類的私有屬性的定義方式是:”var 屬性名“
var age = _age;//私有屬性
var salary = _salary;//私有屬性
/*定義私有屬性Age的對外公開訪問方法*/
this.setAge = function (intAge) {
age = intAge;
}
/*定義私有屬性Age的對外公開訪問方法*/
this.getAge = function () {
return age;
}
//定義Person類的公開方法(特權方法),類的公開方法的定義方式是:”this.functionName=function(){.....}“
this.Show = function () {
document.writeln("在公開方法里面訪問類的私有屬性是允許的,age=" + age + "\t" + "salary=" + salary);//在公開方法里面訪問類的私有屬性是允許的
}
//公共方法
this.publicMethod = function () {
document.writeln("在公開方法里面訪問類的私有方法是允許的");
privateFn();//在公開方法里面調用類的私有方法
privateFn2();//在公開方法里面調用類的私有方法
}
/*
定義Person類的私有方法(內部方法),
類的私有方法的定義方式是:”function functionName(){.....}“,
或者 var functionName=function(){....}
*/
function privateFn() {
document.writeln("我是Person類的私有函數privateFn");
}
var privateFn2 = function () {
document.writeln("我是Person類的私有函數privateFn2");
}
}
2、原型方式
需要說明的是,使用原型方式編寫JavaScript類是無法給類添加私有屬性和私有方法的,使用原型方式添加的屬性和方法都是public的。
/*定義一個Person類*/
function Person(_name,_age,_weight,_height){
this.init(_name,_age,_weight,_height);
}
/*使用原型的方式定義Person類的public屬性:name,age,weight,height,使用原型的方式添加的屬性都是public的*/
Person.prototype.name;
Person.prototype.age;
Person.prototype.weight;
Person.prototype.height;
/*使用原型的方式給Person類添加public方法,使用原型的方式添加的方法都是public的*/
/*使用原型的方式給Person類添加init方法*/
Person.prototype.init = function(_name,_age,_weight,_height) {
if(_name != undefined && _age!=undefined && _weight!=undefined && _height!=undefined){
this.name = _name;
this.age = _age;
this.weight=_weight;
this.height=_height;
document.writeln("this.name="+this.name+",this.age="+this.age+",this.weight="+this.weight+",this.height="+this.height);
}
}
/*使用原型的方式給Person類添加show方法*/
Person.prototype.show = function(){
document.writeln("show method");
}
/*定義類Person2*/
function Person2(){
}
/*使用原型方式給類定義public屬性和public方法更加優雅的寫法*/
Person2.prototype = {
name:"",//public屬性
age:0,//public屬性
weight:0,//public屬性
height:0,//public屬性
/*public方法*/
init:function(_name,_age,_weight,_height) {
this.name = _name;
this.age = _age;
this.weight=_weight;
this.height=_height;
document.writeln("this.name="+this.name+",this.age="+this.age+",this.weight="+this.weight+",this.height="+this.height);
},
/*public方法*/
show:function(){
document.writeln("show method");
}
};