原型

原型的实际应用jQueryzepto的简单应用

zepto如何使用原型

(function (window) {
  var zepto = {};

  function Z(dom, selector) {
    var i, len = dom ? dom.length : 0;
    for (i = 0; i < len; i++) {
      this[i] = dom[i]
    }
    this.length = len;
    this.selector = selector || '';
  }

  zepto.Z = function (dom, selector) {
    return new Z(dom, selector);
  };

  zepto.init = function (selector) {
    var slice = Array.prototype.slice;
    var dom = slice.call(document.querySelectorAll(selector));
    return zepto.Z(dom, selector);
  };

  var $ = function (selector) {
    return zepto.init(selector);
  };

  window.$ = $;

  $.fn = {
    constructor: zepto.Z,
    css: function (key, value) {
      alert('css')
    },
    html: function (value) {
      alert('html')
    }
  };
  zepto.Z.prototype = Z.prototype = $.fn;
})(window);

jQuery如何使用原型

var jQuery = function (selector) {
  return new jQuery.fn.init(selector)
};

//定义构造函数
var init = jQuery.fn.init = function (selector) {
  var slice = Array.prototype.slice;
  var dom = slice.call(document.querySelectorAll(selector));

  var i, len = dom ? dom.length : 0;
  for (i = 0; i < len; i++) {
    this[i] = dom[i]
  }
  this.length = len;
  this.selector = selector || '';
};

//初始化 jQuery.fn
jQuery.fn = jQuery.prototype = {
  constructor: jQuery,
  css: function (key, value) {
  },
  html: function (value) {
  }
};

//定义原型
init.prototype = jQuery.fn;