【发布时间】:2011-05-05 02:25:57
【问题描述】:
我如何在构建类后引用添加到类中的所有函数? (可能作为一个数组)并且不使用prototype。
我已经建立了一个类foo(),并想添加功能以添加新功能
以后可以用。
var f = new foo();
然后
f.addfunc('bar',function(){/*code*/});
以便以后可以使用f.bar();。
使用 foo.__func_expose(funcname , function ); 导出 (?) 函数不起作用。
(可能我做错了。)似乎有一个错误。 (详见下面的代码)。
目的是拥有一个包含所有添加的函数和实际函数的数组,以便以后调用/替换它。
在 javascript 中从公共函数中公开新函数名是否可行?
我想实现一些目标
var MyExtendedFoo = foo();
MyExtendedFoo.__func_add("bar",(function (a, b){
alert('called : anon-func-we-named-bar'); return 2+a+b;}));
MyExtendedFoo.bar(1,3); // <---this does not work.
// It should alert a message, then return 6.
此刻的实际代码是
function foo(){
// we store reference to ourself in __self
this.__self = arguments.callee;
var self = arguments.callee;
// array that holds funcname , function
if (!self.__func_list_fname) self.__func_list_fname = [];
if (!self.__func_list_func) self.__func_list_func = [];
// allow foo.__func_expose(); register to public
self['__func_expose'] = function(){
var self = __self;
for(var i=0;i<self.__func_list_fname.length;i++){
self[''+self.__func_list_fname[i]+''] = self.__func_list_func[i];
// <---This part seems wrong. How do I do it?
};
return __self.__func_return();
};
// allow foo.__func_add( funcname , function );
self['__func_add'] = function(f,v){
var self = __self;
self.__func_list_fname.push(f);
self.__func_list_func.push(v);
// tell itself to expose the new func as well as the old ones.
return __self.__func_expose();
};
// build obj from known list and return it.
self['__func_return'] = function(){
var self = __self;
var obj = {};
obj['__func_expose'] = self['__func_expose'];
obj['__func_add'] = self['__func_add'];
obj['__func_return'] = self['__func_return'];
for(var i=0;i<self.__func_list_fname.length;i++){
obj[''+self.__func_list_fname[i]+''] = self.__func_list_func[i];
};
return obj;
};
// Return ourself so we can chain
return self.__func_return();
}
是的。我已经完成了我的家庭作业。我仍然缺少一些东西。
- http://www.crockford.com/javascript/private.html
- https://developer.mozilla.org/en/Introduction_to_Object-Oriented_JavaScript
- http://www.stackoverflow.com/questions/55611/javascript-private-methods
@philgiese 框架很好,但在这里我们要避免依赖,并保持轻量级。
此外,它没有乐趣,是吗 :-) 不要误会,我并不反对使用原型。
【问题讨论】:
-
你想要实现的目标与
var f = new foo(); f.bar = function() { ... };有什么不同??? -
为什么要避开
prototype? -
公平的问题。我需要一个表示已添加函数的数组。所以
foo.__func_add('bar', ... ).__func_add('doe', ... )...在以后的生活中,foo.RetAllFuncAdded()之类的会返回['bar','doe', ... ]。 -
Philgiese 不会被注意到您的评论;您应该将它(作为评论)添加到他的答案中。
标签: javascript oop function methods