js类的几种写法

我们常用的有以下几种方法来用JavaScript写一个“类”:

 

1. 构造函数(public属性和方法)

1: function Person(iName, iAge){ 
 2:  this.name=iName; //public
 3:  this.age=iAge; //public 
 4:  this.ShowStudent=function(){ //public
 5:  alert(this.name);
 6:  };

 7: }

 


缺点很明显,类的属性和方法,很容易被外部修改。

以上的属性和方法都是public的。下面的例子给出private和public的属性和方法。

 

 

2. 构造函数(public, private属性和方法)

 1: function Person(iName, iAge){ 
 2:  //private field 
 3:   var name = iName;    
 4:  var age = iAge;
 5:      
 6:  //private method 
 7:   var privatefn = function(){     
 8:    alert(name); 
 9:   } 
 10:  
 11:  return {
 12:     //public field 
 13:  Name: "hello " + name,
 14:  Age: "hello " + age,
 15:  
 16:  ShowStudent: function(){
 17:  privatefn(); 
 18:  alert(this.Name); 
 19:  }
 20:  };
 21: }

 

调用:(new Person("xiao","10")).ShowStudent();

 

 

3. 原型方法(prototype)

 1: function c(){}
 2: c.prototype={
 3:  name: "init value a",
 4:  setName: function(iName){
 5:  this.name=iName;
 6:  },
 7:  getName: function(){
 8:  alert(‘hello from c, name: ‘ + this.name);
 9:  }
 10: };
 11: (new c).getName(); // 输出hello from c, name: init value a

 

 

4. 构造函数+原型方法(prototype)

 1: function Person(iName) {
 2:  this.name = iName;
 3: };
 4:  
 5: Person.prototype={
 6:  getName: function(){
 7:  return this.name;
 8:  }
 9: };
 10:  
 11: //调用
 12: var b = new Person("jack");
 13: alert(b.getName()); 

一般多会用上面这种写法。

5. 构造函数+原型方法(prototype)- 节省内存的写法

 1: function Person(iName, iAge){
 2:  this.name=iName;
 3:  this.age=iAge;
 4:  
 5:  //对象实例都共享同一份方法不造成内存浪费
 6:  if(typeof Person._initialized == "undefined"){
 7:  Person.prototype.ShowStudent=function(){
 8:  alert(this.name);
 9:  };
 10:  Person._initialized=true;
 11:  }
 12: } 
 13: //调用
 14: (new Person("jack","20")).ShowStudent();

 

以上的实现方法如果不用_initialized的方法,也可以指向一个外部函数,道理一样。

 

6. JavaScript类的单例(Singleton)模式写法

 1: var MyNamespace = {};
 2: MyNamespace.Singleton = (function() {
 3:  var uniqueInstance; // Private attribute that holds the single instance.
 4:  function constructor() { // All of the normal singleton code goes here.
 5:  // Private members.
 6:  var privateAttribute1 = false;
 7:  var privateAttribute2 = [1, 2, 3];
 8:  function privateMethod1() {
 9:  //...
 10:  }
 11:  function privateMethod2(args) {
 12:  //...
 13:  }
 14:  return { // Public members.
 15:  publicAttribute1: true,
 16:  publicAttribute2: 10,
 17:  publicMethod1: function() {
 18:  // ...
 19:  },
 20:  publicMethod2: function(args) {
 21:  // ...
 22:  }
 23:  }
 24:  }
 25:  return {
 26:  getInstance: function() {
 27:  if(!uniqueInstance) { // Instantiate only if the instance doesn‘t exist.
 28:  uniqueInstance = constructor();
 29:  }
 30:  return uniqueInstance;
 31:  }
 32:  }
 33: })();
 34:  
 35: //调用: 
 36: MyNamespace.Singleton.getInstance().publicMethod1();

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。