简体   繁体   中英

JavaScript call variable as Object and Function like jQuery

I'm trying to create a library for mobile and I want to be able to call the object as function and object like jquery does.

Example:

var test = function(elm) {

    this.ajax = function(opt) { ... }
    if ( elm ) {
       var elms = document.querySelectorAll(elm);
    }
}

and I want to be able to call it like this:

test("#id");

and like this:

test.ajax(opts);

LE: Thank you guys for your fast responses!

In JavaScript, a function is actually just an object with code attached.

So instead of a plain object:

var test = {};
test.ajax = function() { /* ajax */ };

... use a function:

var test = function() { /* test */ };
test.ajax = function() { /* ajax */ };

In both cases, you can access test.ajax . The extra thing with the function is that you can call test .

Or mabye something like this:

Object.prototype.Test = function( method ) {
    var method = method || null;
    var elms   = null;

    /* Methods */
    this.ajax = function(opt){
        console.log('You called ajax method with options:');
        console.log(opt);
    }
    /* Logic */
    if (method in this) this[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
    else {
        try {
            elms = document.querySelectorAll(method);
        }
        catch(e) {
            console.log(e.message);
        }
    }

}
window.onload = function() {
    Test('ajax', {'url':'testurl.com'});
    Test('#aid');  
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM