javascript模拟面向对象的类

模拟面向对象的类
第一种方法:

//定义类属性和方法方法之一
function Test(){
    this.id = 001;
    this.name = "Tom";
    this.fun = function(){};
}
//定义类属性和方法方法之二
Test.prototype.otherName = "Lucy";
//访问
var test = new Test();
alert(test.name);
alert(test.otherName);

第二种方法:

缺点:不能实现私有属性和私有方法,实例对象之间也不能共享数据(也就是无法实现static)。

//类的定义
var Test = {
    name: "hehe",
    fun: function(){}
};
//类的实例化
var test = Object.create(Test);
alert(test.name);
test.fun();

//************************************
//注意:Object.create()方法是Javascript的国际标准ECMAScript第五版(目前通行的是第三版),提出的,IE9+以及firefox、chrome等支持(也就是支持html5的基本都支持),IE8-不支持。
//遇到不支持的浏览器,使用一下兼容代码。
//************************************
if (!Object.create) {
    Object.create = function (o) {
       function F() {}
      F.prototype = o;
      return new F();   //相当于第一种实现类的方法
    };
  }

第三种方法:

//思路
var Tom = {
    //定义一个构造函数
    creat: function(){
        //在这个构造函数中定义一个对象,作为返回值
        //那么,在使用的时候,直接Tom.creat()就可以实例化对象了
        var test = {};
        test.name = "jack";
        test.fun = function(){};
        //*******************************************************************
        //私有属性,只要不定义到test对象中,则是私有的,外界无法访问、子类无法继承
        //*******************************************************************
        var p = 0;   //私有属性
        test.getp = function(){return p;}; //为外界提供访问私有属性的接口
        //******************************************************************* 
        //test.setSex = function(x){Tom.sex = x;};
        //test.getSex = function(){return Tom.sex;};
        //*******************************************************************
        return test;
    },
    sex: "man"      //静态属性,相当于static
}
//使用
var hehe = Tom.creat();
hehe.fun();   //访问类中的方法
alert(hehe.p);  //错误,私有属性不能直接访问,需要通过hehe.getp()访问

//*****************************************************
//继承,如现在有个TomSon的类要继承Tom这个类,如下(私有属性不可继承,如有父类留有外部访问接口,比如上面的getp()则可以通过getp()访问)
//*****************************************************
var TomSon {
    creat: function(){
        var test = Tom.creat();  //把Tom类实例化到TomSon中,然后自己再扩展。
        test.age = 18;           //TomSon自己扩展的属性
        return test;
    }
}
//使用
var haha = TomSon.creat();
haha.fun();       //父类的方法
alert(haha.age);  //子类的属性

//*******************************************************************
//static静态,在构造函数外定义,把接口留在构造函数内即可。
//*******************************************************************
//使用,以Tom类为例,创建两个实例
 var tom1 = Tom.creat();
 var tom2 = Tom.creat();
 alert(tom1.getSex());    //man
 alert(tom2.getSex());   //man
 tom1.SetSex("women");
 alert(tom1.getSex());    //women
 alert(tom2.getSex());   //women
 //发现,改了tom1的sex之后,tom2也跟着变,所以sex是static的。
 alert(Tom.sex);        //直接用类名也可以访问static属性

你可能感兴趣的:(javascript模拟面向对象的类)