这两种方式都使用相同的调用机制。
显然,我想使用最好的方式,但这也许只是一个偏好问题?
就风格而言,我喜欢对象文字表示法,因为它提供了封装。
函数表示法:
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];
}
}
最佳答案
你正在做两件有些不同的事情。
第一个示例创建一个函数对象并为其分配属性。
第二个示例创建具有这些属性的普通对象。
第一个在您的示例中确实没有多大实际意义。您可以使用函数对象来分配属性,但为什么要这样做呢?这些属性对函数的调用没有影响。
"Style-wise I like the Object Literal Notation because it provides enclosure."
我不知道什么是“enclosure”。这听起来像是封装和闭包的结合,而对象字面量两者都不提供。
回到第一部分,想象一下如果您创建了这些对象中的任何一个......
var TextProcessor = new Number();
var TextProcessor = new Boolean();
var TextProcessor = new Date();
...然后为其分配属性。这会起作用,但这样做会很奇怪。该对象是 Number
、Boolean
或 Date
的事实与手头的任务关系不大。
这实际上就是您将属性分配给 Function
对象时所做的事情。
关于javascript - 函数与对象文字表示法 - 有区别吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10079544/