javascript 函数是对象吗? [英] javascript functions are objects?
问题描述
我在 Javascript 问题上苦苦挣扎了一段时间,但我无法在网上找到解释.我想这是因为我没有输入正确的关键字,这也可能与我为什么为此苦苦挣扎有关.
I am struggling with a Javascript question for some time now and I was not able to find an explanation on the web. I guess it is because I do not enter the right keywords which might also be related to why I am struggling with this at all.
我的基本假设是可以更改对象:
My basic assumption is that it is possible to alter objects:
> var x = {'n': 2};
> x['n']
2
> x['n'] = 3;
3
哇哦,那行得通.但仍然(函数也是对象):
pheww that worked. But still (functions are objects, too):
> var addn = function(a) {
var n = 2;
return n + a;
}
> addn(3);
5
> addn['n'] = 3;
3
> addn(3);
5
这次我没能改变'n'.有没有办法在保持功能风味的同时解决这个问题?与完全面向对象相反.我有一个相关的问题是如何维护函数的依赖关系,例如为了测试 - 再次不去面向对象?当然,我正在寻找解决方案,但如果可能的话,我也想了解 Javascript 中的哪种机制让我陷入困境.
This time I was not able to change 'n'. Is there a way to fix this while keeping the functional flavor? As opposed to going fully OO. A related question I have would be how to maintain dependencies of functions for the purpose of for example testing - again w/o going OO? Of cause I am looking for a solution but if possible I would also like to understand which mechanism in Javascript makes me struggling.
干杯,
标记
免责声明:通过提及 OO,我无意反对 OO.我也无意反对 VI 或 Emacs.如果我以某种方式伤害了您的感情,请跳过这一点.
Disclaimer: By mentioning OO I do not intent to say anything against OO. And I do not intent to say anything against VI or Emacs either. If I somehow hurt your feelings please skip this one.
推荐答案
如果我正确理解您的问题,您可以为匿名函数命名并通过该名称访问函数对象的属性:
If I understand your question correctly, you can give a name to your anonymous function and access the function object's properties through that:
var addn = function func(a) {
return func.n + a;
};
addn['n'] = 3;
addn(3); // returns 6
这篇关于javascript 函数是对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!