百良西瓜

导航

JavaScript 设计模式 - 工具函数

1、类式继承,模拟面向对象语言的继承方式

function extend(subClass, superClass) {
  var F = function() {};
  F.prototype = superClass.prototype;
  subClass.prototype = new F();
  subClass.prototype.constructor = subClass;

  subClass.superclass = superClass.prototype;
  if(superClass.prototype.constructor == Object.prototype.constructor) {
    superClass.prototype.constructor = superClass;
  }
}

 

2、克隆,实现原型式继承,是 JavaScript 中独有的以对象为蓝本的继承方式

function clone(object) {
  var F = function() {};
  F.prototype = object;
  return new F();
}

 

3、JavaScript 中模拟面向对象语言接口(Interface)的实现方式

// 首先,声明 Interface 构造函数 
var Interface = function(name, methods) {
  if(arguments.length != 2) {
    throw new Error("Interface constructor called with " + arguments.length
      + " arguments, bue expected exactly 2.");
  }

  this.name = name;
  this.methods = [];
  for(var i = 0, len = methods.length; i < len; i++) {
    if(typeof methods[i] !== 'string') {
      throw new Error("Interface constructor expects method names to be "
        + "passed in as a string.");
    }

    this.methods.push(methods[i]);
  }
}

// 为 Interface 定义一个类方法,用于检测 object 对象是否实现了指定接口的方法?
Interface.ensureImplements = function(object) {
  if(arguments.length < 2) {
    throw new Error("Function Interface.ensureImplements called with "
      + arguments.length + " arguments, bue expected at least 2.");
  }

  for(var i = 1, len = arguments.length; i < len; i++) {
    var interface = arguments[i];
    if(interface.constructor !== Interface) {
      throw new Error("Function Interface.ensureImplements expects arguments "
        + "two and above to be instances of Interface.");
    }

    for(var j = 0, methodsLen = interface.methods.length; j < methodsLen; j++) {
      var method = interface.methods[j];
      if(!object[method] || typeof method !== 'function') {
        throw new Error("Function Interface.ensureImplements: object "
          + "does not implement the " + interface.name
          + " interface. Method " + method + " was not found.");
      }
    }
  }
};

/// 以下为示例 ///////////////////////////////////////////////////////////////////////////////////////////////////////////

// 声明接口,只需声明,无需实现
var Composite = new Interface('Composite', ['add', 'remove', 'getChild']);

// 声明接口,只需声明,无需实现
var FormItem = new Interface('FormItem', ['save']);

  // 声明实现的类

  function MenuItem(id, method, action) {

    ...

    this.show = function(object) {

      Interface.ensureImplements(this, [Composite, MenuItem]);

      // 保证类对象实现了 Composite, MenuItem 接口,才能执行下面的逻辑

      ...

    }

    ...

  }

 

 

  

posted on 2015-12-17 04:31  百良西瓜  阅读(145)  评论(0编辑  收藏  举报