A better JavaScript constructor pattern. Abstracts away the bad parts of new
, but maintains a distinction between instance and static members, unlike the illustrious Object.create
.
Server-side (Node.js):
$ npm install func
Client-side (component(1)):
$ component install shannonmoeller/func.js
...args
Zero or more arguments to pass to init
.
Returns an instance of Func
. Calls this.init
with provided arguments.
var Func = require('func');
Func.prototype.init = function (foo, bar) {
this.yell(foo, bar);
};
Func.prototype.yell = function (baz, bat) {
console.log(baz, bat);
};
Func('hello', 'world'); // logs 'hello world'
Same as Func([...args])
. Rest in peace new
.
new Func('hello', 'world'); // logs 'hello world'
Nice try. Same as Func([...args])
.
Func.call({}, 'hello', 'world'); // logs 'hello world'
Guess. Yep, same as Func([...args])
.
Func.apply({}, ['hello', 'world']); // logs 'hello world'
prot
An object containing instance members.
stat
An object containing static members.
Returns a function whose prototype
object is an instance of Func
—a subclass if you must. Conveniently copies given instance and static members to the appropriate objects. The new function is also blessed with its own .extend()
, you know, for kids.
var Func = require('func');
var Kid = Func.extend();
var Grandkid = Kid.extend({
bar: 'world',
init: function (foo) {
console.log(foo, this.bar);
}
}, {
yell: function (foo, bar) {
alert(foo + ' ' + bar);
}
});
Grandkid('hello'); // logs 'hello world'
Grandkid.yell('hello', 'world'); // alerts 'hello world'
- Douglas Crockford (Prototypal Inheritance (or, the birth of
Object.create
) and Bad Parts.) - John Resig (Simple JavaScript Inheritance)
- Dean Edwards (A Base Class for JavaScript Inheritance)
MIT