Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 250
cigraphics Avatar asked Sep 22 '26 08:09

cigraphics


2 Answers

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.

like image 148
pimvdb Avatar answered Sep 24 '26 20:09

pimvdb


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');  
}
like image 42
Aivar Avatar answered Sep 24 '26 20:09

Aivar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!