2013年1月28日月曜日

new and not new

x() instanceof x と new x() instanceof x を同時に満たすような x の作り方。

var x = (function () {
    var constructor = function (args) {
        /* constructor */
    };

    /* other definitions */

    var exports = function (args) {
        return new constructor(args);
    };

    constructor.prototype.constructor = exports;
    exports.prototype = constructor.prototype;

    return exports;
}());

とやると、x() instanceof x && new x() instanceof x となる。

jQuery も似たような事やってる。https://github.com/jquery/jquery/blob/master/src/core.js