LoginSignup
4
5

More than 5 years have passed since last update.

JavaScriptでnewを使わずnewを再現する

Last updated at Posted at 2015-02-09

/**
 * usage
 *   var obj = _new(Constructor, arg1, arg2, arg3);
 */
function _new(Constructor /* ...args */) {
    if(typeof Constructor !== "function") {
        throw TypeError();
    }

    var args = Array.prototype.slice.call(arguments, 1);
    var obj = Object.create(Constructor.prototype);
    var objc = Constructor.apply(obj, args);

    if(objc == null) {
        return obj;
    }

    switch(typeof objc) {
        case "number":
        case "string":
        case "boolean":
            return obj;
        default:
            return objc;
    }
}

// Cクラス
function C(c) {
    this.c = c;
}

var c = _new(C, "hello");
console.log(c.c);               // => hello
console.log(c instanceof C);    // => true


// Cクラスを継承したDクラス
function D(c, d) {
    C.call(this, c);
    this.d = d;
}

D.prototype = Object.create(C.prototype);

var d = _new(D, "hello", " world");
console.log(d.c + d.d);         // => hello world
console.log(d instanceof C);    // => true
console.log(d instanceof D);    // => true



// オブジェクトを返すコンストラクタのEクラス
function E(e) {
    this.e = e;
    return [1, 2, 3];
}

var e = _new(E, "hello");
console.log(e.e);               // undefined
console.log(e);                 // [1, 2, 3]


4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5