javascript函数是对象吗? [英] javascript functions are objects?

查看:80
本文介绍了javascript函数是对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间以来,我一直在努力解决Javascript问题,并且无法在网络上找到解释。我想这是因为我没有输入正确的关键字,这也可能与我为什么挣扎在一起。



我的基本假设是,有可能改变对象:

 > var x = {'n':2}; 
> x ['n']
2
> x ['n'] = 3;
3

有效的工作。但仍然(函数也是对象):

 > var addn = function(a){
var n = 2;
return n + a;
}

> ADDN(3);
5
> addn ['n'] = 3;
3
> ADDN(3);
5

这次我无法改变'n'。有没有办法解决这个问题,同时保持功能的味道?而不是完全OO。我有一个相关的问题,就是如何维护函数的依赖关系,以便进行测试 - 再次不用OO?因为我正在寻找一个解决方案,但如果可能的话,我还想了解Javascript中的哪个机制让我挣扎。



干杯,



Mark



免责声明:
提到面向对象,我不打算对面向对象说任何话。而且我也不打算对VI或Emacs发表任何言论。如果我不知何故伤害了你的感情,请跳过这一段。

匿名函数并通过它访问函数对象的属性:

pre $ var c addn = function func(a){
return func .n + a;
};

addn ['n'] = 3;
addn(3); //返回6


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

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.

Cheers,

Mark

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆