/**
* 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]
More than 5 years have passed since last update.
Register as a new user and use Qiita more conveniently
- You get articles that match your needs
- You can efficiently read back useful information
- You can use dark theme
List of users who liked
45