扩展现有对象以添加其他JavaScript原型方法
假设我有一个类似下面的函数,它创建了一个非常简单的微库:扩展现有对象以添加其他JavaScript原型方法,javascript,prototype,extend,Javascript,Prototype,Extend,假设我有一个类似下面的函数,它创建了一个非常简单的微库: var microLib = function(selector) { var el; var selectorEngine = function(selector) { var selector_value = selector.slice(1); return document.getElementById(selector_value); }; el = se
var microLib = function(selector) {
var el;
var selectorEngine = function(selector)
{
var selector_value = selector.slice(1);
return document.getElementById(selector_value);
};
el = selectorEngine(selector);
Element.prototype.func_1 = function(){
return 'first';
};
Element.prototype.func_2 = function(){
return 'second';
};
return el;
};
window._$ = microLib;
此脚本允许我编写如下代码:
var elem = _$("#div_with_id"); //some element on my web page
console.log(elem.func_2()); //outputs 'second' in the console
现在,我正在寻找一种方法,在一段补充代码中扩展\u$
,以添加额外的元素
console.log(elem.func_3()); //to output 'third' in the console
我之所以需要这样做,是因为这个扩展需要发生在另一个JavaScript文件中,否则我只需要添加另一个方法就可以了
我怎样才能做到这一点呢?下面是我建议的方法的一个示例:
JS:
所以我在上读了这篇文章,作者建议使用对象包装器。通过快速搜索,我找到了以下帖子:
再加上@DRD的答案,我更新了代码:
(function() {
var microLib = function (selector){
return new Dom(selector);
};
function Dom(selector)
{
var selector_value = selector.slice(1);
this.element = document.getElementById(selector_value);
}
Dom.prototype.func_1 = function(){
return 'first';
};
Dom.prototype.func_2 = function(){
return 'second';
};
microLib.extend = function(name, func){
Dom.prototype[name] = func;
};
window._$ = microLib;
})();
然后,当您想要扩展和添加另一个函数时,请在之后执行以下操作:
_$.extend('func_3', function(){ //this is inline with my earlier question
return 'third';
});
工作起来很有魅力!与扩展元素相比,这无疑是更安全的选择。prototype
这是一个非常不清楚、非常糟糕的做法(没有非常好的理由扩展元素是很糟糕的),而且非常。。。没用??既然你已经在做这种修改元素.prototype
的可怕的实践,只需以同样的方式添加func_3
。我不明白问题出在哪里。既然您正在创建自己的微库,那么为什么您需要修改Element.prototype?在函数的原型上创建方法,以便这些方法对选定的元素进行操作。通过这种方式,您可以实现\u$(#div_with_id)。func_3()
与元素func_3()
。确切地说,是扩展\u$
而不是元素。请参阅我答案中更详细的示例。谢谢。使用了它的某些部分来修复我的代码。干杯
_$.extend('func_3', function(){ //this is inline with my earlier question
return 'third';
});