2012-03-05 80 views
-1

我想知道是否有辦法讓單個語句中分配'myFields'的所有屬性?將屬性添加到函數返回的對象中?

這工作:

function fieldMap(namesString) { 
    var result = {}; 
    var names = namesString.split(' '); 
    for (index in names) { 
     var name = names[index]; 
     result[name] = name + '/text()'; 
    } 
    return result; 
} 
var myFields = fieldMap('title rating author url'); 
myFields['cover']="@cover"; 

這不起作用:

var myFields = fieldMap('title rating author url')['cover']='@cover'; 
+0

你是說你要分配相同的值,在對象的所有屬性一個單一的聲明? – 2012-03-05 14:11:19

回答

0

如果你想改變在一個聲明中的所有對象的屬性,你必須自己寫一個映射方法:

function fieldMap(namesString) { // Mike Lin's version 
    var result = {}; 
    var names = namesString.split(' '); 
    for (var i=0; i<names.length; i++) { 
     var name = names[i]; 
     result[name] = name + '/text()'; 
    } 
    return result; 
} 

Object.prototype.map = function(callbackOrValue){ 
    /* better create an object yourself and set its prototype instead! */ 
    var res = {}; 
    for(var x in this){ 
     if(typeof this[x] === "function") 
      res[x] = this[x]; 
     if(typeof callbackOrValue === "function") 
      res[x] = callbackOrValue.call(this[x]); 
     else 
      res[x] = callbackOrValue; 
    } 
    return res; 
} 

然後你可以使用

var myFields = fieldMap('title rating author url').map(function(){return '@cover'}; 
    /* ... or ... */ 
var myFields = fieldMap('title rating author url').('@cover'); 

但是,如果你想設置myFields,並改變在相同的步驟值,試試這個:

var myFields; 
(myFields = fieldMap('title rating author url'))['cover']='@cover';