Javascript 可以像对象一样访问的jQuery风格函数
我正在为web服务创建一个AJAX API,我希望能够像调用jQuery一样调用访问器。 jQuery似乎能够将“jQuery”作为函数执行,但也可以使用它直接访问作为函数结果的对象,例如:Javascript 可以像对象一样访问的jQuery风格函数,javascript,jquery,Javascript,Jquery,我正在为web服务创建一个AJAX API,我希望能够像调用jQuery一样调用访问器。 jQuery似乎能够将“jQuery”作为函数执行,但也可以使用它直接访问作为函数结果的对象,例如: jQuery(); jQuery.each({}); 这是我似乎无法实现的技巧: myAPI('foo'); //output: 'foo' myAPI('foo').changeBar(); //output: 'foo' 1 myAPI.changeBar(); //Error: not a func
jQuery();
jQuery.each({});
这是我似乎无法实现的技巧:
myAPI('foo'); //output: 'foo'
myAPI('foo').changeBar(); //output: 'foo' 1
myAPI.changeBar(); //Error: not a function
我已经看到了类似问题的答案,这些答案很有帮助,但并没有真正回答我的问题
-非常有趣,但您无法访问f.prototype设置的方法
-使用多个操作来创建对象,而不是单个函数
这是我的密码:
(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所做的事情无关,因为它既是一个函数又是一个伪命名空间。您不需要任何奇怪的东西,就可以使用$.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"
先告诉我吧。这就是全部!在你的最后一点上,这里有一篇关于使用函数构造函数(有或没有
new
)的文章,因为jQuery确实像工厂一样工作。这样我就可以获得我想要的行为,而不必使用jQuery的原型魔法。这让事情变得容易多了。感谢分享!如何制作一些ike Constructor.fn.function要添加到实例函数吗?@Kluska000Constructor.prototype.each=Constructor.each;
例如