OO.js | |
|---|---|
| A few simple helper methods to help you do object-oriented javascript Author: Arjan van der Gaag InstallationSimple include the script on your page:
...or
This library is not yet published as an NPM package, but you
can download it manually and install it yourself if you want
to using Usage example
Use properties like normal, even those that are set using the parent's constructor function:
Note how the child object decorates the parent object:
Also note that a method can be bound to an object:
Finally, we have mixed in a module, so its properties become available: | |
| | (function() {
var OO = { |
Generics | |
| Publish the current version of the library, should you ever need it at runtime. | version: '0.1.0', |
OO helper methods | |
| Extend one object with the properties of another. This essentially mixes in all properties of | extend: function(host, guest) {
for(var key in guest) {
if(guest.hasOwnProperty(key)) {
host[key] = guest[key];
}
}
}, |
| Simulate inheritence of one object ( This creates a ghost-class that shares its prototype with the parent, and an instanceof which acts as prototype for the child. This allows the child to share the prototype properties of the parent, without being able to modify them directly (we don't want them to be the same properties). Furthermore, this extends the child constructor itself with any
properties of the parent constructor, and it sets a | inherits: function(child, parent) {
this.extend(child, parent);
function Ghost() { this.constructor = child; }
Ghost.prototype = parent.prototype;
child.prototype = new Ghost;
child.__super__ = parent.prototype;
}, |
| Bind a function to a particular context. Being able to dynamically set the execution context of a
function using Example: | bind: function(context, fn) {
return function() {
return fn.apply(context, arguments);
};
}
}; |
Exporting to gobal objectMake the OO object available on the window object -- the global object when running inside a browser -- or as an export, so you can use it as a CommonJS module. | if(typeof module === 'undefined' || !module.exports) {
window.OO = OO;
} else {
module.exports = OO;
}
})();
|