我正在为Web服务创建一个AJAX API,我希望能够调用类似jQuery的访问器。 jQuery的似乎是能够执行“jQuery的”作为一个功能,而且还用它来直接访问是功能EG的结果对象:可以像对象一样访问的jQuery风格的函数
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));
我敢肯定,我失去了一些东西简单:(
打我给它。这里的所有都是它的!关于最后一点,下面是一篇关于使用带有或不带'new'的函数构造函数的文章,http://js-bits.blogspot.com/2010/08/constructors-without-using-new.html,因为jQuery可以工作像工厂一样。 – 2012-02-10 16:43:39
所以我可以得到我想要的行为,而不必使用jQuery的原型魔法。这使事情变得更容易。感谢分享! – underscorePez 2012-02-13 09:19:13