JavaScript编写类

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 + " " + "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");
}
};













 

原文地址:https://www.cnblogs.com/rency/p/9023143.html