Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/368.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在JavaScript中同时作为函数的变量_Javascript_Jquery - Fatal编程技术网

在JavaScript中同时作为函数的变量

在JavaScript中同时作为函数的变量,javascript,jquery,Javascript,Jquery,我真的很想实现这样的东西 myVar.myAnotherVar; myVar.myMethod(); myVar("sample text"); jQuery就是这样实现的 jQuery.fn; jQuery.ajax(); jQuery("#myBtn"); 如何实现像jQuery这样的东西,将所有内容保存在一个名称空间中?这和原型有关吗?如何使用变量同时作为函数调用 谢谢:)JavaScript中的函数是对象,您可以像任何其他对象一样任意向它们添加属性: function foo() {

我真的很想实现这样的东西

myVar.myAnotherVar;
myVar.myMethod();
myVar("sample text");
jQuery就是这样实现的

jQuery.fn;
jQuery.ajax();
jQuery("#myBtn");
如何实现像jQuery这样的东西,将所有内容保存在一个名称空间中?这和原型有关吗?如何使用变量同时作为函数调用


谢谢:)

JavaScript中的函数是对象,您可以像任何其他对象一样任意向它们添加属性:

function foo() {
    // Code for when you call `foo` goes here
}
foo.someData = "bar";
foo.someFunction = function() {
    // Code for when you call `foo.someFunction` goes here
};
jQuery所做的事情稍微复杂一些,但有点不同寻常,有两种方式:

  • jQuery
    函数(通常别名为
    $
    )只是对创建新对象的构造函数调用的包装。(构造函数名为
    init

  • 他们在名为
    fn
    jQuery
    函数的属性中添加了对
    init
    函数的
    prototype
    属性的引用。这两个属性(
    jQuery.fn
    init.prototype
    )都引用了当您使用
    new init
    时将成为实例原型的对象

  • 他们还引用了
    jQuery.prototype
    中的同一个对象,尽管
    jQuery
    没有用作构造函数。这样,$的
    $()实例将
    为true

  • 但你不必为了做你所描述的事情而去做那些事情。你当然可以,但你不必

    如果您想做这两件事,基本结构如下所示:

    var foo = function() {
        // The public function
        function foo(args, here) {
            return new init(args, here);
        }
    
        // The hidden constructor function
        function init(args, here) {
            // ...do something with `this`, perhaps
        }
    
        // The object that becomes the prototype of instances created via `new init`
        foo.fn = foo.prototype = init.prototype = {
            // An instance-specific function, like jQuery's `css`
            instanceMethod: function() {
                // Has access to `this`
            }
        };
    
        // A random piece of "static" (not instance-specific) data
        foo.someData = "bar";
    
        // A "static" (not instance-specific) function, like jQuery's `$.ajax`
        foo.staticMethod = function() {
            // Doesn't have (useful) access to `this`
        };
    
        return foo;
    }();
    

    @Mahan:最基本的是,是的。@Mahan:我添加了一个更复杂的例子来说明jQuery在上面所做的事情,希望这会有用。