在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