[英]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. 我正在尝试为移动设备创建一个库,我希望能够像jquery一样将对象称为函数和对象。
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! LE: 谢谢你们的快速反应!
In JavaScript, a function is actually just an object with code attached. 在JavaScript中,函数实际上只是附加代码的对象。
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
. 在这两种情况下,您都可以访问
test.ajax
。 The extra thing with the function is that you can call test
. 该功能的额外功能是你可以调用
test
。
Or mabye something like this: 或者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.