0

I pass an object literal to a function like this:

pre( {model:'MUserTry'} ); 

I then wish to augment it, but I end up writing over it like this.

    pre : function( o_p ) {
        o_p = {
            result: '0',
            page  : {}
        };

model is now gone as o_p is completely new

What is the best way to append object properties.

Do you have to explicitly define them now.

o_p.result = 0;
o_p.page = {};

or is there a function that will allow me to write out the object literal and combine them?

kind of like this

object1.push (object2 );
4

3 回答 3

3

要添加新的对象属性或方法,请使用点运算符:

obj.dog = "woof";

这也是等价的:

obj["dog"] = "woof";
于 2012-07-05T21:28:23.093 回答
2

您可以通过分配给它们来添加属性:

o_p.result = '0';

这不会创建新对象并因此保留您的model属性。

于 2012-07-05T21:28:08.047 回答
2

在您的代码中,局部变量 o_p 通过分配重新定义:

function( o_p ) {
    // assign a new value to local variable o_p
    // object passed as an argument is untouched
    o_p = {
        result: '0',
        page  : {}
    };
}

你可以像这样合并你的对象:

function( o_p ) {
    var mergee = {
        result: '0',
        page  : {}
    };
    for (var attrname in mergee) { o_p[attrname] = mergee[attrname]; }    
}

或者,如果你可以使用 JQuery,你可以只使用 extend 方法:

function( o_p ) {
    var mergee = {
        result: '0',
        page  : {}
    };
    $.extend(o_p, mergee);
}
于 2012-07-05T21:39:23.690 回答