1

我有一个对象构造函数,并且我定义了一种方法来使用 json-object 作为输入参数为对象属性设置新值,我的解决方案正在运行,但我怀疑是否有最好的方法来做到这一点?

任何使用OOP的答案将不胜感激。


这是我的代码:

//Object constructor
function searchOption(o) {
   o = o || {};
   this.Word = o.Word || "";
   this.SubCategories = o.SubCategories || [];
   this.Page = o.Page || 1;
   this.Sort = o.Sort || "desc";
   this.ItemsView = o.ItemsView || 18;
   //Method to set new values, preserving untouched properties
   this.set = function (x) { $.extend(this, x); };
}

(function() {
    var search = new searchOption({ Word:"canela", ItemsView:6 });
    console.log(search);
    search.set({ Word:"VIAJE", Page:3, Sort:"asc" });
    console.log(search);
})();
4

3 回答 3

4

我会this.set从构造函数中删除方法并prototype改用。

//Object constructor
function searchOption(o) {
   o = o || {};
   this.Word = o.Word || "";
   this.SubCategories = o.SubCategories || [];
   this.Page = o.Page || 1;
   this.Sort = o.Sort || "desc";
   this.ItemsView = o.ItemsView || 18;
}

//Method to set new values, preserving the untouched properties
searchOption.prototype.set = function(x) {
    searchOption($.extend(this, x));
}
于 2013-10-31T19:40:16.660 回答
1

Since $.extend() extends the first passed object you even do not need to call constructor function once again in your set method

searchOption.prototype.set = function(x) {
    $.extend(this, x);
};

Fiddle here: http://jsbin.com/eHodoqA/1/edit

NOTE:

If you want SubCategories to be merged as well - pass true as first parameter to $.extend that will trigger deep clone (see http://api.jquery.com/jQuery.extend/#jQuery-extend-deep-target-object1-objectN)

于 2013-10-31T20:13:18.133 回答
1

在内存消耗方面有更好的方法,因为您可以通过prototype. 这同样适用于函数。

undefined您可以使用辅助函数来实现这一新设计,该函数仅在所需成员不是默认值或与默认值不同时才复制它们。

此外,作为约定,构造函数以大写字母开头,属性通常为 lowerCamelCased。这些命名约定被广泛使用,我强烈建议您遵循它们。

以下设计用于学习目的,除非您计划有很多实例,否则没有必要。SearchOption

function applyConfig(obj, config, props) {
    var i = 0,
        len = props.length,
        k, v;

    for (; i < len; i++) {
        if (
            config.hasOwnProperty(k = props[i]) && typeof (v = config[k]) !== 'undefined' //ingore undefined values
            //let default values be shared between instances
            && v !== obj[k]
        ) {
            obj[k] = v;
        }
    }
}

function SearchOption(config) {

    config = config || {};

    //handle all immutable values
    applyConfig(this, config, ['word', 'page', 'sort', 'itemsView']);

    this.subCategories = config.subCategories || [];
}


SearchOption.prototype = {
    constructor: SearchOption,
    //keeping default values on the prototype is memory efficient
    //since they get shared between instances, however we should only use
    //this approach for immutable values.
    word: '',
    page: 1,
    sort: 'desc',
    itemsView: 18,
    //it's better to have functions on the prototype too
    set: function (values) {
        //not sure why you were doing searchOptions(...)? It looks very wrong
        //since the function will get executed in the global object's context (window)

        //note that with the following, we will shadow any default prototype
        //values, unlike when we called the constructor.
        $.extend(this, values);
    }
};

var so1 = new SearchOption(), //share same word
    so2 = new SearchOption(), //share same word
    so3 = new SearchOption({
        word: 'test'
    });

console.log('so1:', so1.word, 'so2:', so2.word, 'so3:', so3.word);

console.log(so1);
于 2013-10-31T20:27:35.673 回答