现在的位置: 首页 > 综合 > 正文

Prototype.js 框架分析(待续)

2019年10月29日 ⁄ 综合 ⁄ 共 5418字 ⁄ 字号 评论关闭

Prototype.js 架构分析

注:本文中使用"类"说法只是为了统一说法

0.Prototype.js创建类的框架结构
var ClassA = {
    'K' : function(){},
    'L' : .....,
    'M' : .....
};
或者
var ClassA = {
    function _K() { }

    function _L() { }

    function _M() { }

    //< 类对处暴露的接口
    return {
        'K' : _K,
        'L' : _L
    };
};

1.关键类Class
关键类Class提供两个关键方法create,Methods来创建类及为该类添加方法.
其中create基于原型来创建继承类。(进一步了解原型继承请见<Javascript高级程序设计(第三版)>)(在这里为这本书做下广告,这是精通js必备书籍)
不多说直接晒源码:
/* Based on Alex Arnell's inheritance implementation. */

/*
function $A(iterable) {
  if (!iterable) return [];
  if ('toArray' in Object(iterable)) return iterable.toArray();
  var length = iterable.length || 0, results = new Array(length);
  while (length--) results[length] = iterable[length];
  return results;
}
*/

var Class = (function() {

  var IS_DONTENUM_BUGGY = (function(){
    for (var p in { toString: 1 }) {
      if (p === 'toString') return false;
    }
    return true;
  })();

  function subclass() {};
  function create() {
    var parent = null, properties = $A(arguments);
    if (Object.isFunction(properties[0]))
      parent = properties.shift();

    function klass() {
      this.initialize.apply(this, arguments);
    }

    Object.extend(klass, Class.Methods);
    klass.superclass = parent;
    klass.subclasses = [];

    if (parent) {
      subclass.prototype = parent.prototype;
      klass.prototype = new subclass;
      parent.subclasses.push(klass);
    }

    for (var i = 0, length = properties.length; i < length; i++)
      klass.addMethods(properties[i]);

    if (!klass.prototype.initialize)
      klass.prototype.initialize = Prototype.emptyFunction;

    klass.prototype.constructor = klass;
    return klass;
  }

  function addMethods(source) {
    var ancestor   = this.superclass && this.superclass.prototype,//< 在运行环境 Class.create中this指向klass对象
        properties = Object.keys(source);

    if (IS_DONTENUM_BUGGY) {
      if (source.toString != Object.prototype.toString)
        properties.push("toString");
      if (source.valueOf != Object.prototype.valueOf)
        properties.push("valueOf");
    }

    for (var i = 0, length = properties.length; i < length; i++) {
      var property = properties[i], 
          value = source[property];
      if (ancestor && Object.isFunction(value) && value.argumentNames()[0] == "$super") {
        var method = value;
        value = (function(m) {
          return function() { return ancestor[m].apply(this, arguments); };
        })(property).wrap(method);

        value.valueOf = method.valueOf.bind(method);
        value.toString = method.toString.bind(method);
      }
      this.prototype[property] = value;
    }

    return this;
  }

  return {
    create: create,
    Methods: {
      addMethods: addMethods
    }
  };
})();

有性趣的直接上官网prototypejs.org下载源码.

2.其于Class类扩展原生的JS对象Object,Function,Date,RegExp,String,Array,Number
1).扩展Object原型
    extend(Object, {
        extend:        extend,
        inspect:       inspect,
        toJSON:        NATIVE_JSON_STRINGIFY_SUPPORT ? stringify : toJSON,
        toQueryString: toQueryString,
        toHTML:        toHTML,
        keys:          Object.keys || keys,
        values:        values,
        clone:         clone,
        isElement:     isElement,
        isArray:       isArray,
        isHash:        isHash,
        isFunction:    isFunction,
        isString:      isString,
        isNumber:      isNumber,
        isDate:        isDate,
        isUndefined:   isUndefined
    });

2).扩展Function.prototype原型
Object.extend(Function.prototype, (function() {
    return {
        argumentNames:       argumentNames,
        bind:                bind,
        bindAsEventListener: bindAsEventListener,
        curry:               curry,
        delay:               delay,
        defer:               defer,
        wrap:                wrap,
        methodize:           methodize
    };
})());

3).扩展Date.prototype原型
(function(proto) {
  function toISOString() { }
  function toJSON() { }

  if (!proto.toISOString) proto.toISOString = toISOString;
  if (!proto.toJSON) proto.toJSON = toJSON;
})(Date.prototype);

4).扩展Regex原型
RegExp.prototype.match = RegExp.prototype.test;
RegExp.escape = function(str) {
  return String(str).replace(/([.*+?^=!:${}()|[\]\/\\])/g, '\\$1');
};

5).扩展String
    a).扩展String对象
    Object.extend(String, {
        interpret: function(value) {
        return value == null ? '' : String(value);
        },
        specialChar: {
        '\b': '\\b',
        '\t': '\\t',
        '\n': '\\n',
        '\f': '\\f',
        '\r': '\\r',
        '\\': '\\\\'
        }
    });
    
    b).扩展String.prototype
    Object.extend(String.prototype, (function() {
        return {
            gsub:           gsub,
            sub:            sub,
            scan:           scan,
            truncate:       truncate,
            strip:          String.prototype.trim || strip,
            stripTags:      stripTags,
            stripScripts:   stripScripts,
            extractScripts: extractScripts,
            evalScripts:    evalScripts,
            escapeHTML:     escapeHTML,
            unescapeHTML:   unescapeHTML,
            toQueryParams:  toQueryParams,
            parseQuery:     toQueryParams,
            toArray:        toArray,
            succ:           succ,
            times:          times,
            camelize:       camelize,
            capitalize:     capitalize,
            underscore:     underscore,
            dasherize:      dasherize,
            inspect:        inspect,
            unfilterJSON:   unfilterJSON,
            isJSON:         isJSON,
            evalJSON:       NATIVE_JSON_PARSE_SUPPORT ? parseJSON : evalJSON,
            include:        include,
            startsWith:     startsWith,
            endsWith:       endsWith,
            empty:          empty,
            blank:          blank,
            interpolate:    interpolate
        };
    })());

6).扩展Array
Object.extend(arrayProto, {
    _each:     _each,
    clear:     clear,
    first:     first,
    last:      last,
    compact:   compact,
    flatten:   flatten,
    without:   without,
    reverse:   reverse,
    uniq:      uniq,
    intersect: intersect,
    clone:     clone,
    toArray:   clone,
    size:      size,
    inspect:   inspect,
    concat:    concat,
    indexOf:   indexOf,
    lastIndexOf:lastIndexOf
});

7).扩展Number.prototye
Object.extend(Number.prototype, (function() {

  return {
    toColorPart:    toColorPart,
    succ:           succ,
    times:          times,
    toPaddedString: toPaddedString,
    abs:            abs,
    round:          round,
    ceil:           ceil,
    floor:          floor
  };
})());

3.Ajax类

4.Dom操作

5.基于Sizzle的CSS Selector(在jQuery中基于Sizzle建立其基于CSS选择器来检索Dom对象的核心功能)

6.表单处理

抱歉!评论已关闭.