2012-03-05 79 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';