函数与对象文字注释 - 是否存在差异? [英] Function vs. Object Literal Notaion - is there a diifference?
问题描述
这两种方式都使用相同的呼叫机制。
Both these ways work using the same call mechanism.
显然,我想用最好的方式,但也许这只是一个偏好的问题?
Obviously, I want to use the best way, but perhaps it is just a matter of preference?
样式方面我喜欢Object Literal Notation,因为它提供了外壳。
Style-wise I like the Object Literal Notation because it provides enclosure.
函数符号:
var TextProcessor = function()
{
};
TextProcessor.unEscape = function( second_split )
{
var element;
for( element in second_split )
{
second_split[element] = second_split[element].replace( '**', '*', 'g' );
second_split[element] = second_split[element].replace( '|*', '|', 'g' );
}
return second_split;
};
TextProcessor.pullBullet = function( text )
{
var pattern = /<(.+)_([a-z]){1}>$/;
return pattern.exec( text );
};
TextProcessor.pullDomain = function( text )
{
return text.match( /:\/\/(www\.)?(.[^\/:]+)/ )[2];
};
对象文字符号
/**
*TextProcessor
*/
var TextProcessor =
{
unEscape: function( text )
{
var index;
for( index in second_split )
{
text[index] = text[index].replace( '**', '*', 'g' );
text[index] = text[index].replace( '|*', '|', 'g' );
}
return second_split;
},
pullBullet: function( text )
{
var pattern = /<(.+)_([a-z]){1}>$/;
return pattern.exec( text );
},
pullDomain: function( text )
{
return text.match( /:\/\/(www\.)?(.[^\/:]+)/ )[2];
}
}
推荐答案
你我做了两件不同的事情。
You're doing two somewhat different things.
-
第一个例子创建一个函数对象并为其分配属性。
The first example creates a function object and assigns properties to it.
第二个示例创建一个包含这些属性的普通对象。
The second example creates a plain object with those properties.
第一个在你的例子中确实没有多少实际意义。您可以使用函数对象来分配属性,但为什么会这样?这些属性对函数的调用没有影响。
The first one really doesn't make much practical sense in your example. You can use a function object to assign properties, but why would you? Those properties have no impact on the invocation of the function.
Style -wise我喜欢Object Literal Notation,因为它提供了外壳。
我不知道 封闭是。它听起来像是封装和闭包的组合,其中一个对象文字也没有提供。
I don't know what "enclosure" is. It sounds like a combination of encapsulation and closure, of which an object literal provides neither.
回到第一部分,想象一下,如果你创建了这些对象中的任何一个......
Getting back to the first part, imagine if you created any one of these objects...
var TextProcessor = new Number();
var TextProcessor = new Boolean();
var TextProcessor = new Date();
...然后将属性分配给它。它会起作用,但这样做会很奇怪。对象是 Number
, Boolean
或 Date
与手头的任务没有多大关系。
...and then assigned the properties to it. It would work, but it would be an odd thing to do. The fact that the object is a Number
, Boolean
, or Date
has little relevance to the task at hand.
当您将属性分配给函数$时,这实际上是您正在做的事情c $ c> object。
That's effectively what you're doing when you assign the properties to a Function
object.
这篇关于函数与对象文字注释 - 是否存在差异?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!