javascript 仿jQuery的无new构造函数

jQuery是一个快速、简洁的JavaScript框架,是继Prototype之后又一个优秀的JavaScript代码库(或JavaScript框架)。jQuery设计的宗旨是“write Less,Do More”,即倡导写更少的代码,做更多的事情。它封装JavaScript常用的功能代码,提供一种简便的JavaScript设计模式,优化HTML文档操作、事件处理、动画设计和Ajax交互。

熟练掌握【构造开发模式】的开发者肯定对jQuery的无new实例化对象感兴趣。我们在工作中,通常都是通过手动 new 来实例化自己写的构造函数。

 

下面自己模仿jQuery手写了一个无new的构造函数

    /* 匿名函数 传入 window 值全局变量成为局部变量 */
    (function(window,undefined) {
        /* 申明一个名为jQuery 的函数*/
        function jQuery(selector) {
            /* 返回 jQuery 实例 */
            return new jQuery.prototype.init(selector);
        }
        /* 为jQuery函数原型添加一个初始化 init 方法 */
        jQuery.prototype.init=function (selector) {
            this.el=document.querySelectorAll(selector)[0];
        };
        /* 为jQuery函数原型添加一个 html 方法 */
        jQuery.prototype.html=function(str){
            if(str){
                this.el.innerHTML=str;
            }else {
                return this.el.innerHTML;
            }
            return this;
        };
        /* 为jQuery函数原型添加一个 color 方法 */
        jQuery.prototype.color=function(rgb){
            if(rgb){
                this.el.style.color=rgb;
            }
            return this;
        };
        /* 将jQuery的原型 赋值给初始化方法的原型*/
        jQuery.prototype.init.prototype = jQuery.prototype;
        /* 设置jQuery函数的别名 $ 并设置为window全局对象的属性 */
        window.$=window.jQuery=jQuery;
    })(window,undefined);

使用说明:


123
$("#div1").html('

[email protected]

').color("#ff0000");

运行效果:

javascript 仿jQuery的无new构造函数_第1张图片

各位读者可以自动复制后运行一下看效果,实现过程已在源码处注释。

作者:黄河爱浪 QQ:1846492969,邮箱:[email protected]

公众号:web-7258,本文原创,著作权归作者所有,转载请注明原链接及出处。

更多精彩文章,请扫下方二维码关注我的公众号

你可能感兴趣的:(javascript)