在JavaScript中,有两种模式,我想衡量使用一个和另一个的好处。是什么和回访功能,例如返回一个对象之间的区别:返回函数与返回对象
var returnFunction = function(name,age){
var n = name;
var a = name;
return function(){
anotherFunc : function(){},
oneMoreFunc : function(){}
}
}
我返回一个包含两个函数的函数,并获得私有变量的名字和年龄。我明白我可以调用returnfunction,并且我知道我可以像构造函数一样使用它。我想知道,什么是这种风格的VS好处:
var returnObject = function(name,age){
var n = name;
var a = age;
return {
anotherFunc:function(){},
oneMoreFunc:function(){},
};
}
- 是否有性能损失?
- 这只是一个风格问题吗?
- 对这个或那个有任何好处,还是我只是在推翻这个?
编辑:
至于选项A,我引用从Javascript这个特殊的语法:好的部分
Function.prototype.method = function(name, func) {
this.prototype[name] = func;
return this;
};
String.method('deentityify', function() {
// The entity table. It maps entity names to
// characters.
var entity = {
quot: '"',
lt: '<',
gt: '>'
};
// Return the deentityify method.
return function() {
// This is the deentityify method. It calls the string
// replace method, looking for substrings that start
// with '&' and end with ';'. If the characters in
// between are in the entity table, then replace the
// entity with the character from the table. It uses
// a regular expression (Chapter 7).
return this.replace(/&([^&;]+);/g,
function(a, b) {
var r = entity[b];
return typeof r === 'string' ? r : a;
}
);
};
}());
选项A是为了复制这句法一个人为的例子。
'功能'总是会比调用'对象'吃更多的资源。 –
第一个不行。它返回一个函数,它除了定义和放弃另外两个函数外什么也不做。 –
@NicholasHazel如果函数是在一个对象中呢? – Julio