Prototype的base和string類

var Prototype = {

  Version: '1.5.0_rc0',

  ScriptFragment: '(?:<script.*?>)((/n|/r|.)*?)(?:<//script>)',

 

  emptyFunction: function() {},

  K: function(x) {return x}

}

/*------聲明一個類-------------------*/

var Class = {

  create: function() {

    return function() {

      this.initialize.apply(this, arguments);

    }

  }

}

/*------抽像類------------------*/

var Abstract = new Object();

/*------通過屬性拷貝,實現繼承和擴展------------------*/

Object.extend = function(destination, source) {

  for (var property in source) {

    destination[property] = source[property];

  }

  return destination;

}

/*------返回目標對像的說明------------------*/

Object.inspect = function(object) {

  try {

    if (object == undefined) return 'undefined';

    if (object == null) return 'null';

    return object.inspect ? object.inspect() : object.toString();

  } catch (e) {

    if (e instanceof RangeError) return '...';

    throw e;

  }

}

/*------返回一個方法實例,用於綁定方法------------------*/

Function.prototype.bind = function() {

  var __method = this, args = $A(arguments), object = args.shift();

  return function() {

    return __method.apply(object, args.concat($A(arguments)));

  }

}

/*------返回一個方法實例,用於綁定事件,將事件綁定到對像上------------------*/

Function.prototype.bindAsEventListener = function(object) {

  var __method = this;

  return function(event) {

    return __method.call(object, event || window.event);

  }

}

 

Object.extend(Number.prototype, {

  toColorPart: function() {

    var digits = this.toString(16);

    if (this < 16) return '0' + digits;

    return digits;

  },

 

  succ: function() {

    return this + 1;

  },

 

  times: function(iterator) {

    $R(0, this, true).each(iterator);

    return this;

  }

});

 

var Try = {

  these: function() {

    var returnValue;

 

    for (var i = 0; i < arguments.length; i++) {

      var lambda = arguments[i];

      try {

        returnValue = lambda();

        break;

      } catch (e) {}

    }

 

    return returnValue;

  }

}

 

/*--------------------------週期性的調用某事件或方法類似於settimeout------------------------------------------------*/

 

var PeriodicalExecuter = Class.create();

PeriodicalExecuter.prototype = {

  initialize: function(callback, frequency) {

    this.callback = callback;

    this.frequency = frequency;

    this.currentlyExecuting = false;

 

    this.registerCallback();

  },

 

  registerCallback: function() {

    setInterval(this.onTimerEvent.bind(this), this.frequency * 1000);

  },

 

  onTimerEvent: function() {

    if (!this.currentlyExecuting) {

      try {

        this.currentlyExecuting = true;

        this.callback();

      } finally {

        this.currentlyExecuting = false;

      }

    }

  }

}

/*--------------------------string對像擴展------------------------------------------------*/

Object.extend(String.prototype, {

  gsub: function(pattern, replacement) {

    var result = '', source = this, match;

    replacement = arguments.callee.prepareReplacement(replacement);

 

    while (source.length > 0) {

      if (match = source.match(pattern)) {

        result += source.slice(0, match.index);

        result += (replacement(match) || '').toString();

        source  = source.slice(match.index + match[0].length);

      } else {

        result += source, source = '';

      }

    }

    return result;

  },

 

  sub: function(pattern, replacement, count) {

    replacement = this.gsub.prepareReplacement(replacement);

    count = count === undefined ? 1 : count;

 

    return this.gsub(pattern, function(match) {

      if (--count < 0) return match[0];

      return replacement(match);

    });

  },

 

  scan: function(pattern, iterator) {

    this.gsub(pattern, iterator);

    return this;

  },

 

  truncate: function(length, truncation) {

    length = length || 30;

    truncation = truncation === undefined ? '...' : truncation;

    return this.length > length ?

      this.slice(0, length - truncation.length) + truncation : this;

  },

 

  strip: function() {

    return this.replace(/^/s+/, '').replace(//s+$/, '');

  },

 

  stripTags: function() {

    return this.replace(/<//?[^>]+>/gi, '');

  },

 

  stripScripts: function() {

    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');

  },

 

  extractScripts: function() {

    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');

    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');

    return (this.match(matchAll) || []).map(function(scriptTag) {

      return (scriptTag.match(matchOne) || ['', ''])[1];

    });

  },

/*--------------------------執行子串中的字符串-----------------------------------------------*/

  evalScripts: function() {

    return this.extractScripts().map(function(script) { return eval(script) });

  },

/*--------------------------html進行轉義-----------------------------------------------*/

  escapeHTML: function() {

    var div = document.createElement('div');

    var text = document.createTextNode(this);

    div.appendChild(text);

    return div.innerHTML;

  },

/*--------------------------html進行轉義的相反操作-----------------------------------------------*/

  unescapeHTML: function() {

    var div = document.createElement('div');

    div.innerHTML = this.stripTags();

    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';

  },

/*--------------------------將字符串轉換成聯合數組-----------------------------------------------*/

  toQueryParams: function() {

    var pairs = this.match(/^/??(.*)$/)[1].split('&');

    return pairs.inject({}, function(params, pairString) {

      var pair = pairString.split('=');

      params[pair[0]] = pair[1];

      return params;

    });

 

/*--------------------------將字符串轉換成數組-----------------------------------------------*/

  toArray: function() {

    return this.split('');

  },

/*--------------------------去除字符串中的短劃線,並尊尋駱駝命名法則-----------------------------------------------*/

  camelize: function() {

    var oStringList = this.split('-');

    if (oStringList.length == 1) return oStringList[0];

 

    var camelizedString = this.indexOf('-') == 0

      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)

      : oStringList[0];

 

    for (var i = 1, len = oStringList.length; i < len; i++) {

      var s = oStringList[i];

      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);

    }

 

    return camelizedString;

  },

/*--------------------------返回字符串的說明文字-----------------------------------------------*/

  inspect: function() {

    return "'" + this.replace(////g, '////').replace(/'/g, '///'') + "'";

  }

});

/*--------------------------新增方法-----------------------------------------------*/

String.prototype.gsub.prepareReplacement = function(replacement) {

  if (typeof replacement == 'function') return replacement;

  var template = new Template(replacement);

  return function(match) { return template.evaluate(match) };

}

 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章