浅析JavaScript的写类方式(2)


  本文标签:JavaScript

  这篇开始会记录一些写类的工具函数,通过上篇我们知道本质上都是 构造函数+原型  。理解了它碰到各式各样的写类方式就不惧怕了  。以下列举的有的是工作中碰到的,有的是从书籍或网上收集的  。见过的朋友就忽视它吧  。

  上一篇:浅析JavaScript的写类方式(1)

  51CTO推荐专题:JavaScript函数式编程

  构造函数 + 原型 直接组装一个类;同一构造函数将组装出同一类型

  1. /**  
  2.  * $class 写类工具函数之一  
  3.  * @param {Function} constructor  
  4.  * @param {Object} prototype  
  5.  */ 
  6. function $class(constructor,prototype) {  
  7.     var c = constructor || function(){};  
  8.     var p = prototype || {};  
  9.     c.prototype = p;  
  10.     return c;  

  用构造函数来生成类实例的属性(字段),原型对象用来生成类实例的方法  。

  1. //构造函数  
  2. function Person(name) {  
  3.     this.name = name;  
  4. }  
  5. //原型对象  
  6. var proto = {  
  7.     getName : function(){return this.name},  
  8.     setName : function(name){this.name = name;}   
  9. }  
  10. //组装  
  11. var Man = $class(Person,proto);  
  12. var Woman = $class(Person,proto); 

  这时候已经得到了两个类Man,Woman  。并且是同一个类型的  。测试如下:

  1. console.log(Man == Woman); //true  
  2. console.log(Man.prototype == Woman.prototype); //true 

  创建对象看看

  1. var man = new Man("Andy");  
  2. var woman = new Woman("Lily");  
  3.  
  4. console.log(man instanceof Man); //true  
  5. console.log(woman instanceof Woman); //true  
  6. console.log(man instanceof Person); //true  
  7. console.log(woman instanceof Person); //true 

  ok,一切如我们所期望  。但是有个问题,下面代码的结果输出false

  1. console.log(man.constructor == Person);//false
     

  这让人不悦:从以上的代码看出man的确是通过Man类new出来的 var man = new Man("Andy"),那么对象实例man的构造器应该指向Man,但为何事与愿违呢?

  原因就在于$class中重写了Person的原型:c.prototype = p;

  好了,我们把$class稍微改写下,将方法都挂在构造器的原型上(而不是重写构造器的原型),如下:
 

  1. function $class(constructor,prototype) {  
  2.     var c = constructor || function(){};  
  3.     var p = prototype || {};  
  4. //  c.prototype = p;  
  5.     for(var atr in p){  
  6.         c.prototype[atr] = p[atr];  
  7.     }     
  8.     return c;  

  原文链接:http://www.cnblogs.com/snandy/archive/2011/03/06/1972254.html