将属性添加到函数返回的对象?

时间:2012-03-05 14:00:15

标签: javascript

我想知道是否有办法在单个语句中分配“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';

1 个答案:

答案 0 :(得分: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';