jQuery风格的函数,可以像对象一样访问
jQuery-style function that can be accessed like an object
我正在为web服务创建一个AJAX API,我希望能够调用jQuery-like访问者。jQuery似乎能够将"jQuery"作为一个函数来执行,但也可以使用它直接访问函数EG:的结果对象
jQuery();
jQuery.each({});
这是我似乎无法实现的技巧:
myAPI('foo'); //output: 'foo'
myAPI('foo').changeBar(); //output: 'foo' 1
myAPI.changeBar(); //Error: not a function
我看过类似问题的答案,这些答案很有帮助,但并没有真正回答我的问题。
#8734115-真的很有趣,但你不能访问f.prototype设置的方法。
#2953314-使用多个操作来创建对象,而不是单个函数。
这是我的代码:
(function(window) {
var h = function(foo) {
// The h object is actually just the init constructor 'enhanced'
return new h.fn.init(foo);
};
/**
* Methods defined at protoype.
*/
h.fn = h.prototype = {
constructor: h,
init: function(foo) {
console.log(foo);
return this;
},
splice : function () {},
length : 0,
bar : 0,
changeBar : function() {
this.bar++;
return this.bar;
}
};
h.fn.init.prototype = h.fn;
//Publish
window.myAPI =h;
}( window));
我确信我错过了一些简单的东西:(
jQuery正在使用jQuery
作为函数和伪命名空间。也就是说,您可以调用jQuery
:var divs = jQuery("div");
,并且您可以在其上使用属性,例如:jQuery.each(...);
。
这是可能的,因为在JavaScript中,函数是一流的对象,因此您可以向它们添加任意属性:
function foo() {
alert("Foo!");
}
foo.bar = function() {
alert("Bar!");
};
foo(); // "Foo!"
foo.bar(); // "Bar!"
这就是它的全部。
在对bar
的调用中,this
将是foo
函数(因为this
完全由调用的方式决定,而不是由函数的定义位置决定)。jQuery不使用this
来指代自己(通常它使用this
来指代DOM元素,有时指代数组元素等其他东西;当指代自己时,由于它是一个单独的东西,所以它只使用jQuery
)。
现在,您可能需要确保您的函数具有正确的名称(而我在上面分配给bar
的函数是匿名的—属性有名称,但函数没有)。在这种情况下,您可能会进入模块模式:
var foo = (function() {
function foo() {
alert("Foo!");
}
function foo_bar() {
alert("Bar!");
}
foo.bar = foo_bar;
return foo;
})();
foo(); // "Foo!"
foo.bar(); // "Bar!"
这种模式还有一个优点,即您可以在作用域函数(封装其他所有内容的大型匿名函数)中拥有只有您的代码才能使用的私有数据和函数。
var foo = (function() {
function foo() {
reallyPrivate("Foo!");
}
function foo_bar() {
reallyPrivate("Bar!");
}
function reallyPrivate(msg) {
alert(msg);
}
foo.bar = foo_bar;
return foo;
})();
foo(); // "Foo!"
foo.bar(); // "Bar!"
reallyPrivate("Hi"); // Error, `reallyPrivate` is undefined outside of the scoping function
在您的代码中,您将事物分配给函数的prototype
属性。只有当函数被调用为构造函数时(例如,通过new
),这才起作用。执行此操作时,new
创建的对象将接收函数的prototype
属性作为其基础原型。但这是一件完全不同的事情,与jQuery的作用无关,jQuery既是函数,又是伪命名空间。
使用$.each这样的东西不需要任何奇怪的东西您只需将函数附加到函数对象原型对象的
function Constructor() {
if (!(this instanceof Constructor)) {
return new Constructor();
}
}
Constructor.prototype = {
each: function() {
return "instance method";
}
};
Constructor.each = function() {
return "static method";
};
var a = Constructor();
a.each(); //"instance method"
Constructor.each(); //"static method"
- 访问布局信息是否也会导致浏览器重排
- Javascript,访问一个主要对象模块模式中的每个对象
- 如何访问声音管理器2创建的声音对象
- 在Twitter上用ie9中的空白src访问iframe的contentWindow
- JavaScript Pub/Sub属性访问问题
- 从JavaScript访问struts操作中的属性
- 是否可以从父类访问子类的属性
- 如何访问fastOpt.js
- 访问JSON对象内部的数组元素
- 从模块内部访问Express装载路径
- 难以访问的JS环境中的语法错误
- 如何从对象的原型方法访问JavaScript对象属性
- 访问json数组中的对象
- Javascript对象可以像数组一样访问吗?
- jQuery风格的函数,可以像对象一样访问
- 使用 top_of_stack(n).value 访问像堆栈一样的数组
- 像矩阵一样访问对象的javaScript数组
- GM_xmlhttpRequest是否访问网站,就像我在浏览器中访问网站一样
- 使变量像窗口一样可访问
- 像数组一样访问json对象中的元素