Как создать общий родительский класс в Javascript - PullRequest
0 голосов
/ 25 ноября 2011

Я пытаюсь создать классы для Countries, Regions, Cities для отображения Polygons на Google Map.

Все 3 класса будут иметь почти одинаковые методы. Это означает, что я должен скопировать все методы 3 раза, что опять-таки является принципом DRY.

Как я могу извлечь родительский класс из этих дочерних классов? Пример класса Country выглядит как

/*
 *
 *
 *
 */
 function CountryPoly 
 {
   /*
    * Regular Expression Pattern to validate color values.
    */    
   this.colorPattern    = /^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;

   /*
    * Regular Expression Pattern to validate opacity values.
    */    
   this.opacityPattern  = /^0\.[0-9]{1,2}$/;

   /*
    * Array containing the Child objects
    */
    this.children       = [];

   /*
    *  default Polygon options.
    */    
   this.polyOptions = {
    paths:          [],
    strokeColor:    #FF0000,
    strokeOpacity:  0.8,
    strockWeight:   3,
    fillColor:      #FF0000,
    fillOpacity:    0.35
   }
 }

 CountryPoly.prototype = {
  toString: function() 
  {
    return "[object CountryPoly]";
  },

  setStrocColor: function(color)
  {
    if(color && this.colorPattern.test(color)) 
    {
      this.polyOptions.strokeColor = color;
    }  
  },

  setStrokeOpacity: function(opacity)
  {
    if(opacity && this.opacityPattern.test(opacity)) 
    {
      this.polyOptions.strokeOpacity = opacity;
    }  
  },

  setFillColor: function(color) 
  {
    if(color && this.colorPattern.test(color)) 
    {
      this.polyOptions.fillColor = color;
    }  
  },

  setFillOpacity: function(opacity)
  {
    if(opacity && this.opacityPattern.test(opacity)) 
    {
      this.polyOptions.fillOpacity = opacity;
    }  
  },

  setStrockWeight: function(strockWeight) 
  {
    if(strockWeight && !isNaN(parseInt(strockWeight)) && strockWeight < 5)
    {
      this.polyOptions.strockWeight = strockWeight;
    }  
  },

  setCoordinates: function(paths) {
    // check if passed argument is Array.
    if(paths.length) {
      this.polyOptions.paths = paths;
    }
  }

  getChildren: function() {
     // Ajax Request to access child objects.
     // this.children = Ajax Response 
  },

  draw: function() {
    //Draws the Polygon
  }  

 }

Ответы [ 2 ]

1 голос
/ 25 ноября 2011

Вы можете использовать систему javascript prototype, которая хотя и не является классическим ОО через «Классы», но допускает аналогичное поведение и является гораздо более гибкой.

var PolygonBase = function () {};

PolygonBase.prototype.colorPattern = /^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/;
PolygonBase.prototype..opacityPattern  = /^0\.[0-9]{1,2}$/;
// ... etc ...

var Country = function () {};
Country.prototype = new PolygonBase();
Country.prototype.constructor = Country;
0 голосов
/ 25 ноября 2011

Взгляните сюда:

http://ejohn.org/blog/simple-javascript-inheritance/

Пример:

var Person = Class.extend({
  init: function(isDancing){
    this.dancing = isDancing;
  },
  dance: function(){
    return this.dancing;
  }
});
var Ninja = Person.extend({
  init: function(){
    this._super( false );
  },
  dance: function(){
    // Call the inherited version of dance()
    return this._super();
  },
  swingSword: function(){
    return true;
  }
});

var p = new Person(true);
p.dance(); // => true

var n = new Ninja();
n.dance(); // => false
n.swingSword(); // => true

// Should all be true
p instanceof Person && p instanceof Class &&
n instanceof Ninja && n instanceof Person && n instanceof Class
...