Passing object as parameter to constructor function and copy its properties to the new object?
You could do this. There is probably also a jquery way...
function Box(obj) {
for (var fld in obj) {
this[fld] = obj[fld];
}
}
You can include a test for hasOwnProperty if you've (I think foolishly) extended object
function Box(obj) {
for (var fld in obj) {
if (obj.hasOwnProperty(fld)) {
this[fld] = obj[fld];
}
}
}
Edit
Ah, ha! it's jQuery.extend
So, the jQuery way is:
function Box(obj) {
$.extend(this, obj);
}
Simply put this in your constructor
for (var prop in obj) {
if (obj.hasOwnProperty(prop)) {
this[prop] = obj[prop];
}
}
Here's an example with the javascript module pattern:
var s,
NewsWidget = {
settings: {
numArticles: 5,
articleList: $("#article-list"),
moreButton: $("#more-button")
},
init: function(options) {
this.settings = $.extend(this.settings, options);
s = this.settings;
this.bindUIActions();
},
bindUIActions: function() {
s.moreButton.on("click", function() {
NewsWidget.getMoreArticles(s.numArticles);
});
},
getMoreArticles: function(numToGet) {
// $.ajax or something
// using numToGet as param
}
};
$(function(){
NewsWidget.init({
numArticles: 6
});
console.log(s.numArticles);
});