模拟面向对象的类
第一种方法:html
//定义类属性和方法方法之一 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);
第二种方法:html5
缺点:不能实现私有属性和私有方法,实例对象之间也不能共享数据(也就是没法实现static)。chrome
//类的定义 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属性