代码之家  ›  专栏  ›  技术社区  ›  frozen

javascript模拟jQuery语法

  •  2
  • frozen  · 技术社区  · 8 年前

    在jQuery中,“$”别名有许多用途。它在这里的作用类似于一个函数:

    $('#someid')
    

    但也可以将其作为对象:

    $.attr('id', 'hello');
    

    我如何制作一个具有此属性的函数(能够作为自身和方法的对象调用)?

    此外,有时你可以这样连锁:

    $('id').html('<span>Hello</span>);
    

    如何扩展对象以伴随此操作?

    3 回复  |  直到 8 年前
        1
  •  8
  •   Joe Clay    8 年前

    功能 对象,因此可以像对任何其他对象一样向函数添加属性。

    function $(id) {
        // blah blah
    }
    
    $.attr = function (id, attr) {
        // blah blah
    }
    
        2
  •  2
  •   Bakhtiiar Muzakparov    8 年前

    jQuery = function( selector, context ) {
    
            // The jQuery object is actually just the init constructor 'enhanced'
            // Need init if jQuery is called (just allow error to be thrown if not included)
            return new jQuery.fn.init( selector, context );
        },
    
        // Support: Android <=4.0 only
        // Make sure we trim BOM and NBSP
        rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
    
        // Matches dashed string for camelizing
        rmsPrefix = /^-ms-/,
        rdashAlpha = /-([a-z])/g,
    
        // Used by jQuery.camelCase as callback to replace()
        fcamelCase = function( all, letter ) {
            return letter.toUpperCase();
        };
    
    jQuery.fn = jQuery.prototype = {
    
        // The current version of jQuery being used
        jquery: version,
    
        constructor: jQuery,
    
        // The default length of a jQuery object is 0
        length: 0,
    
        toArray: function() {
            return slice.call( this );
        },
    

    它取自中间,因此可以安全地假设jQuery是在代码的前面声明的对象 var jQuery =... 还要记住 $ jQuery 并且它们被连接到 window 全局对象。您可能需要花时间研究一下令人敬畏的开放源码本身,以获得更清晰的想法: https://github.com/jquery/jquery

        3
  •  2
  •   Dr_Derp    8 年前

    Joe正确地回答了如何使“函数”像对象一样工作的问题,所以我不再费心回答这部分了。

    为了能够链接函数调用(这是问题第二部分中发生的情况),您调用的函数需要返回一个对象。它看起来像这样:

    var func = function() {
        this.func2 = function() {
    
            return this;
        };
    
        return this;
    };
    
    // then the following code will work:
    func().func2();
    

    var funcObject = func();
    funcObject.func2();
    

    同样重要的是,jQuery可能没有返回 this ,而是一个包装好的DOM对象,可以具有各种功能,如 attr

    $ = function(id) {
        var wrappedDomObject = getWrappedDomObject(id);
    
        return wrappedDomObject;
    }
    
    // somewhere in jquery
    
    function getWrappedDomObject(id) {
        // some code to get the object
    
        wrappedObject.attr = function(id, value) {
            // some code here
    
            return this;
        }
    
        return wrappedObject;
    }
    

    因为 $ 函数返回一个对象,您可以立即调用 属性 return this .