jQuery风格的函数,可以像对象一样访问

jQuery-style function that can be accessed like an object

本文关键字:访问 一样 对象 风格 函数 jQuery      更新时间:2023-09-26

我正在为web服务创建一个AJAX API,我希望能够调用jQuery-like访问者。jQuery似乎能够将"jQuery"作为一个函数来执行,但也可以使用它直接访问函数EG:的结果对象

jQuery();
jQuery.each({});

这是我似乎无法实现的技巧:

myAPI('foo'); //output: 'foo'
myAPI('foo').changeBar(); //output: 'foo' 1
myAPI.changeBar(); //Error: not a function

我看过类似问题的答案,这些答案很有帮助,但并没有真正回答我的问题。

#8734115-真的很有趣,但你不能访问f.prototype设置的方法。

#2953314-使用多个操作来创建对象,而不是单个函数。

这是我的代码:

(function(window) {
        var h = function(foo) {
                // The h object is actually just the init constructor 'enhanced'
                return new h.fn.init(foo);
        };
        /**
         * Methods defined at protoype.
         */
        h.fn = h.prototype = {
            constructor: h,
            init: function(foo) {
                console.log(foo);
                return this;
            },
            splice : function () {},
            length : 0,
            bar : 0,
            changeBar : function() {
                this.bar++;
                return this.bar;
            }
        };
        h.fn.init.prototype = h.fn;
    //Publish 
    window.myAPI =h;
}( window));

我确信我错过了一些简单的东西:(

jQuery正在使用jQuery作为函数和伪命名空间。也就是说,您可以调用jQuery:var divs = jQuery("div");,并且您可以在其上使用属性,例如:jQuery.each(...);

这是可能的,因为在JavaScript中,函数是一流的对象,因此您可以向它们添加任意属性:

function foo() {
    alert("Foo!");
}
foo.bar = function() {
    alert("Bar!");
};
foo();     // "Foo!"
foo.bar(); // "Bar!"

这就是它的全部。

在对bar的调用中,this将是foo函数(因为this完全由调用的方式决定,而不是由函数的定义位置决定)。jQuery不使用this来指代自己(通常它使用this来指代DOM元素,有时指代数组元素等其他东西;当指代自己时,由于它是一个单独的东西,所以它只使用jQuery)。

现在,您可能需要确保您的函数具有正确的名称(而我在上面分配给bar的函数是匿名的—属性有名称,但函数没有)。在这种情况下,您可能会进入模块模式:

var foo = (function() {
    function foo() {
        alert("Foo!");
    }
    function foo_bar() {
        alert("Bar!");
    }
    foo.bar = foo_bar;
    return foo;
})();
foo();     // "Foo!"
foo.bar(); // "Bar!"

这种模式还有一个优点,即您可以在作用域函数(封装其他所有内容的大型匿名函数)中拥有只有您的代码才能使用的私有数据和函数。

var foo = (function() {
    function foo() {
        reallyPrivate("Foo!");
    }
    function foo_bar() {
        reallyPrivate("Bar!");
    }
    function reallyPrivate(msg) {
        alert(msg);
    }
    foo.bar = foo_bar;
    return foo;
})();
foo();               // "Foo!"
foo.bar();           // "Bar!"
reallyPrivate("Hi"); // Error, `reallyPrivate` is undefined outside of the scoping function

在您的代码中,您将事物分配给函数的prototype属性。只有当函数被调用为构造函数时(例如,通过new),这才起作用。执行此操作时,new创建的对象将接收函数的prototype属性作为其基础原型。但这是一件完全不同的事情,与jQuery的作用无关,jQuery既是函数,又是伪命名空间

使用$.each这样的东西不需要任何奇怪的东西您只需将函数附加到函数对象原型对象的

function Constructor() {
    if (!(this instanceof Constructor)) {
        return new Constructor();
    }
}
Constructor.prototype = {
    each: function() {
        return "instance method";
    }
};
Constructor.each = function() {
    return "static method";
};

var a = Constructor();
a.each(); //"instance method"
Constructor.each(); //"static method"