Javascript:创建对象构造函数

标签 javascript jquery oop

<分区>

我有一个对象构造函数,我定义了一个方法来使用 json 对象作为输入参数为对象属性设置新值,我的解决方案有效,但我怀疑是有最好的方法吗?

任何使用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);
})();

最佳答案

我会从构造函数中删除 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));
}

关于Javascript:创建对象构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19715132/

相关文章:

python - Python 中的面向对象 Tic Tac Toe

javascript - 使用 jQuery 更改属性在 Chrome 中似乎不起作用

javascript - 连接变量名

javascript - 获取 DOM 中的所有 href 链接

jquery - 使用 jQuery 查找包含元素的 ID

javascript - 如何组合单击事件和回车键的按下事件?

python - 在两个类之间传递参数

c++ - dynamic_cast的继承与使用

javascript - MomentJS 与 react 语言

javascript - Mongoose - 从 'pre' 保存 Hook 中的虚拟节点访问数据