我正在尝试为自己构建一个小助手库。首先,出于学习目的,然后我可以扩展它,以便在项目中派上用场。
我对原型引用、闭包和作用域有所了解。我还故意使用模块化模式来制作它,这样我toolbox
就不会污染全局命名空间。我也知道我们可以将原型分配给构造函数,因此构造的对象将保存这些方法。
下面是内容toolbox.js
(function (window) {
var toolbox = (function () {
var toolbox = function(it){
return new pick(it);
}
var pick = function (it){
var craft = document.getElementsByTagName(it);
craft = Array.prototype.slice.call(craft, 0);
return Array.prototype.push.apply(this, craft);
}
pick.prototype = toolbox.prototype = {
raw: function(){
return Array.prototype.slice.call(this, 0);
},
tell: function(secret){
return secret;
}
}
return toolbox;
}());
window.toolbox = toolbox;
})(window);
并调用toolbox
:
toolbox("div"); //returns the desired object with the div collection
toolbox("div").raw(); //returns a raw array with the divs
toolbox().tell("A secret"); //returns "A secret"
toolbox.tell("It's a secret"); //type error: the function has no method like tell (like hell it does...should)
但是像这样修改上面的代码:
var toolbox = (function () {
var toolbox = function(it){
return new pick(it);
}
...
toolbox.tell(secret){ return secret }
return toolbox;
}());
将工作。
所以我的问题是为什么toolbox.prototype = {}
不这样做,而pick.prototype = {}
会pick
继承定义的方法?
我想同时实现这两个目标toolbox.tell("something");
,并且toolbox("div").raw();
不必直接将方法原型化到模块中。
请帮忙!我已经在谷歌上搜索了好几天来学习这些,现在我被困住了。非常感谢您的帮助!
更新
简而言之,jQuery 是如何做到这一点的:
(function( window, undefined ) {
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
}
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
//init stuff
}
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
//extend stuff
};
jQuery.extend({
//extend stuff
});
// Expose jQuery to the global object
return jQuery;
})();
window.jQuery = window.$ = jQuery;
})(window);