This is a JavaScript design pattern called Mixin its main purpose is to extend an object with new properties and values generally referred to as options.
It is used in most of JavaScript librairies such as Three.js
, Vue.js
, jQuery
, dojo
... It helps a lot when defining modules it allow us to extend or override the default options in our module.
You can see from the The Mixin Pattern that:
In JavaScript, we can look at inheriting from Mixins as a means of collecting functionality through extension. Each new object we define has a prototype from which it can inherit further properties. Prototypes can inherit from other object prototypes but, even more importantly, can define properties for any number of object instances. We can leverage this fact to promote function re-use.
Mixins allow objects to borrow (or inherit) functionality from them
with a minimal amount of complexity. As the pattern works well with
JavaScripts object prototypes, it gives us a fairly flexible way to
share functionality from not just one Mixin, but effectively many
through multiple inheritance.
i.e in the following example:
var material = new THREE.MeshBasicMaterial( { color: 0x00ff00 } );
We are setting a new value for the color
option of our instance object.
For further reading you can check dojo .mixin(), JavaScript Mixins: Beyond Simple Object Extension and Mixins, Forwarding, and Delegation articles.
but, How I use this?
Solution:
In your case you can use jQuery .extend() to implement it.
This is how should be your code:
var dot = {
Viewport: function(arguments) {
var defaults = {
container: null
};
this.settings = $.extend({}, defaults, arguments);
if (!this.settings.container) {
var newContainer = document.createElement("div");
newContainer.style.width = window.innerWidth + "px";
newContainer.style.height = window.innerHeight + "px";
newContainer.style.backgroundColor = "red"
document.body.appendChild(newContainer);
}
}
};
This will allow you to use the following syntax to extend your default options and override it:
var oldDiv = document.getElementById("old");
var myViewport = new dot.Viewport({
container: oldDiv
});