繁体   English   中英

JavaScript调用变量作为对象和函数,如jQuery

[英]JavaScript call variable as Object and Function like jQuery

我正在尝试为移动设备创建一个库,我希望能够像jquery一样将对象称为函数和对象。

例:

var test = function(elm) {

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

我希望能够像这样调用它:

test("#id");

和这样:

test.ajax(opts);

LE: 谢谢你们的快速反应!

在JavaScript中,函数实际上只是附加代码的对象。

而不是一个普通的对象:

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

...使用功能:

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

在这两种情况下,您都可以访问test.ajax 该功能的额外功能是你可以调用test

或者mabye这样的事情:

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');  
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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