//在nodejs中,类型定义就像定义函数同样,其实该函数就是Student类的构造函数 var Student=function(){ //若是须要定义该类对象的字段、方法等,需加上this关键字,不然就认为是该函数中的临时变量 this.Name="张三"; this.Age=21; //定义对象方法 this.show=function(){ console.log(this.Name+' '+this.Age); }; }; //类的成员方法也能够在构造方法外定义,需加上prototype关键字,不然就认为是定义类方法(静态方法) Student.prototype.showName=function(){ console.log(this.Name); }; Student.prototype.showAge=function(){ console.log(this.Age); }; //定义类方法(类的静态方法,可直接经过类名访问) Student.showAll=function(name,age){ console.log("showAll "+name+' '+age); }; //定义类的静态字段 Student.TName="李四"; //导出Student类,使其余js文件能够经过require方法类加载该Student模块 module.exports=Student;
其余js中访问student
//使用require方法加载Student模块 var student=require('./Student'); //调用类方法 student.showAll("张思",23); //展示类静态字段 console.log(student.TName); student.TName="王武"; console.log(student.TName); //实例化类对象 var stu=new student(); stu.show(); stu.showName(); stu.showAge();
经过上述例子能够看出,加上关键字prototype表示该变量或者函数是类的成员变量或者成员函数,调用须要new出这个对象。而没有prototype该关键字修饰的变量或者函数,至关于静态变量或者静态函数,能够在外部跟上类名直接调用。