-
原型的实际应用
- 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.querySelector(selector)) return zepto.Z(dom, selector) } var $ = function (selector) { return zepto.init(selector) } window.$=$ $.fn={ constructor:zepto.Z, css:function (key, value) { }, html:function ( value) { } } zepto.Z.prototype=Z.prototype=$.fn })(window)
- jquery中原型的使用
(function (window) { var jQuery = function (selector) { return new jQuery.fn.init(selector); } jQuery.fn = jQuery.prototype = { constructor: jQuery, css: function (key, value) { }, html: function () { } } //定义构造函数 var init = jQuery.fn.init = function (selector) { var slice = Array.prototype.slice var dom = slice.call(document.querySelector(selector)) var i, len = dom ? dom.length : 0 for (i = 0; i < len; i++) { this[i] = dom[i] } this.length = len; this.selector = selector || '' } init.prototype = jQuery.fn window.$ = jQuery })(window)
-
原型如何体现它的扩展性
- jquery 中为什么把原型方法放在$.fn上,是为了扩展插件
$.fn.getNodeName= function () { return this[0].nodeName }
- 好处 只有$ 会暴露在window全局变量
- 将插件扩展统一到$.fn.XXX这个接口,方便使用
原型应用
最新推荐文章于 2022-10-25 19:09:33 发布