空函数在 Javascript 中的使用
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5546113/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Empty Function use in Javascript
提问by duskandawn
I am trying to understand a third party Javascript code. But am not able to figure out what is the use of the below coding style.
我正在尝试了解第三方 Javascript 代码。但我无法弄清楚以下编码风格的用途是什么。
function A(){
}
A.Prop = '23';
A.generate = function(n){
// do something
}
And then it is just used as :
然后它只是用作:
A.generate(name);
Can someone explain what this code is doing. I understand some bit of OO Javascript, but i wonder if this is any other form of extending an object with new properties to it. Though i dont see any "new" keyword being used, to create an object.
有人可以解释一下这段代码在做什么。我了解一些 OO Javascript,但我想知道这是否是将具有新属性的对象扩展到它的任何其他形式。虽然我没有看到使用任何“新”关键字来创建对象。
Any ideas ?
有任何想法吗 ?
Thanks,
谢谢,
回答by Travis Webb
They are creating a namespace. There are many ways to do this, and all are more-or-less equivalent:
他们正在创建一个命名空间。有很多方法可以做到这一点,并且都或多或少是等效的:
A = {
Prop : '23',
generate : function (n) {
// do something
}
};
Or, equivalently:
或者,等效地:
A = { };
A.Prop = '23';
A.generate = function (n) {
// do something
};
Also, if you like being verbose:
另外,如果你喜欢冗长:
A = new Object();
A.Prop = '23';
A.generate = function (n) {
// do something
};
function
is usually used to denote a "class" rather than a "namespace", like so:
function
通常用于表示“类”而不是“命名空间”,如下所示:
A = (function () {
var propValue = '23'; // class local variable
return {
"Prop" : propValue,
"generate" : function (n) {
// do something
}
};
})();
// then I can use A in the same way as before:
A.generate(name);
回答by SLaks
It looks like they're using a dummy function to create a namespace.
看起来他们正在使用一个虚拟函数来创建一个命名空间。
You're right; this is useless.
They should use a normal object instead.
你说得对; 这是没用的。
他们应该改用普通对象。
回答by RobG
A function is an object, there's nothing inherently wrong with using it the way it's been used. However, since the function isn't actually used as a function, it would be better to use an Object. You could also use an Array (which is an object), but the same advice applies.
函数是一个对象,以它的使用方式使用它并没有本质上的错误。但是,由于该函数实际上并未用作函数,因此最好使用 Object。你也可以使用一个数组(它是一个对象),但同样的建议也适用。
Also, identifiers starting with a capital letter are, by convention, reserved for constructors (unless they are all capitals, which are, by convention, for constants) so use a name starting with a lower-case letter.
此外,按照惯例,以大写字母开头的标识符是为构造函数保留的(除非它们都是大写,按照惯例,它们是常量),因此请使用以小写字母开头的名称。