Skip to content

Instantly share code, notes, and snippets.

@halfzebra
Created July 16, 2015 10:29
Show Gist options
  • Save halfzebra/3f836902997aa0493fd1 to your computer and use it in GitHub Desktop.
Save halfzebra/3f836902997aa0493fd1 to your computer and use it in GitHub Desktop.
An example of incapsulation with constructors in JavaScript
(function () {
'use strict';
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) && (!(prop in proto) || proto[prop] !== obj[prop]);
}
var Button = function (settings) {
var settingName;
this.el = document.createElement("button");
for (settingName in this.defaultSettings) {
if (settings !== undefined && hasOwnProperty(settings, settingName)) {
this[settingName] = settings[settingName];
} else {
this[settingName] = this.defaultSettings[settingName];
}
}
this.el.addEventListener(this.event, this.action);
this.el.innerHTML = this.name;
this.el.setAttribute('name', this.machineName);
this.target.appendChild(this.el);
};
Button.prototype.defaultSettings = {
'name': 'Button',
'machineName': 'button',
'event': 'click',
'action': function () {
console.log('Hello, your button is useless, I hope you\'re happy.');
},
'target': document.body
};
var Something = function () {
var self = this,
taskName;
for (var i = 1; i <= 7; i++) {
taskName = 'task' + i;
(function (self, taskName) {
var action = self[taskName];
new Button({
'name': 'Task' + i,
'machineName': taskName,
'action': action.bind(self)
});
}(self, taskName));
}
};
Something.prototype = {};
new Something();
}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment