I'm new to OOP, so I tried to learn from tutorials how to create a class in JavaScript/jQuery. But tutorials don't give you feedback from experienced coders. Is the approach to create a pop-up OK (see below)? I know it works (it's tested), but is it prone to errors or does it have redundancies?
var Popup = function (){
/// PROPERTIES
var new_id="div"+Date.now();
var defaults = {
id: new_id,
container: "body",
height: 200,
width: 200,
text: "<div> created with \"id\" = "+new_id,
x: 100,
y: 100,
position: "absolute",
bgcolor: "red"
};
this.settings=defaults;
/// METHODS
this.create=function (options){
$.extend(this.settings,options);
var html= "<div id=\""+
this.settings.id+"\">"+
this.settings.text+
"</div>";
$(this.settings.container).append(html);
this.update();
};
this.update=function (options) {
$.extend(this.settings,options);
$("#"+this.settings.id).css({
"height":this.settings.height+"px",
"width":this.settings.width+"px",
"position":this.settings.position,
"top":this.settings.y,
"left":this.settings.x,
"background-color":this.settings.bgcolor
});
};
};
/* Popup use:
var pop=new Popup(); // new popup is declared
pop.create({bgcolor:"green"}); // popup appears green instead of read
pop.update({bgcolor:"blue"}); // popup changes to blue
*/
(I know there are a tons of Popup plugins that I could use, but that's irrelevant for my learning goals)
For example, I've realized that this line will cause problems:
this.settings=defaults;
because when "settings" are changed, "defaults" change too (!). Thus, the better alternative is:
this.settings=$.extend(defaults);
or a JavaScript "clone" function like this.