Skip to content
Classes and Modules for Underscore.js
JavaScript
Find file
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Failed to load latest commit information.
datatype.js
readme.textile

readme.textile

Datatype Mixin for Underscore.js

Often you want class like things but writing your objects in the following manner is kind of tedious:

var MyClass = function() {
    this.foo = "foo";
    this.bar = "bar";
};

MyClass.prototype.baz = function() {
    ...
}

MyClass.prototype.woz = function() {
    ...
}

Using datatype.js you can instead write the following:

var MyClass = _.datatype({
    initialize: function() {
       this.foo = "foo";
       this.bar = "bar";
    },

    baz: function () {
    },

    woz: function() {
    }
});

datatype.js doesn’t support datatype inheritance of any kind. However it is sometimes useful to reuse a name. For this purpose there is _.multi. You can use this like so:

var Foo = _.datatype({});
var Bar = _.datatype({});

_.multi("cool", Foo, function(x) {
  console.log("got type Foo!");
});

_.multi("cool", Foobar, function(x) {
  console.log("got type Bar!");
});

var a = new Foo();
var b = new Bar();

_.cool(a);
_.cool(b);
Something went wrong with that request. Please try again.