javascript:如何使模块像对象和函数一样行为?
|
我正在尝试为自己构建一个小帮助程序库。首先,出于学习目的,然后以后我可以扩展它,以便在项目中派上用场。
我对原型的引用,闭包和作用域有所了解。我还故意使用模块化模式进行设置,因此我的
toolbox
不会污染全局名称空间。
我也知道我们可以将原型分配给构造函数,所以构造的对象将包含这些方法。
这是ѭ1的内容
(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\");
和ѭ10without,而不必直接将方法原型化为模块。
请帮忙!我已经搜寻了好几天了,以学习这些知识,现在我陷入了困境。非常感谢您的帮助!
更新
简而言之,这就是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);
没有找到相关结果
已邀请:
3 个回复
纫合峭
基本上是父母与孩子之间的中途。该原型具有父级所具有的全部功能以及您附加的内容-但是,父级没有自己的原型。而且,更令人困惑的是,如果将内容分配给父对象而不是其原型,则多余的内容将不会复制到子对象。奇怪吧? 要解释最后一条语句(使用前面的示例):
这就是为什么您没有
而是
的原因-这些方法存在于原型中。 如果您想使某些东西在对象和原型中都起作用,请将其分配给两者!
因此,现在您可以选择继承的内容和保留在父项中的内容。如果您希望仅对父级可用,则仅将其附加到父级。但是,如果您希望仅在子级上使用它(例如,您没有
,但确实有jQuery()。Self),则将其附加到原型中。如果您想要两者,请将其附加到两者。
凡夕
骇毖煽洁铂
只使用
这会将方法直接添加到工具箱