constructorのおなまえとprototype拡張でうっかり

prototype拡張時のうっかり

今まであまり意識していなかったこともあり,最初???な挙動だったので念のためメモ.

なんでコイツはnewしたあとに,constructor.nameがObjectになってしまうのかしら,という疑問が発端.

protototypeに直接オブジェクトを代入していた

わりと自然にミスしてました.

function Hogehoge() {
	// some logic
}

Hogehoge.prototype = {
	prop      : 123,
	method : function() {}
};

console.log(new Hogehoge().constructor.name);
// -> Object

prototypeにObjectをガッツリ代入してましたprototypeがconstructorになるんですね.prototypeにObjectを代入したことで、constructorも置き換わってしまう.

実際はHogehoge.prototypeにObjectを代入してもHogehoge自体は元の関数なせいか,newできますし,その中のロジック+prototypeに突っ込まれた分のメソッドも問題なく動作します.

パッと見で普通に動作してしまったので,constructorだけなぜObjectなのか気づくの遅れました・・・

正しくはこう

ですね.

function Hogehoge() {
	// some logic
}

Hogehoge.prototype.prop = 123;
Hogehoge.prototype.method : function() {};

console.log(new Hogehoge().constructor.name);
// -> Hogehoge

ばっちりです.

オブジェクト合成的なアレ

Hogehoge.prototype.XXX = YYYを繰り返すのは記述的にアレなので,下記のように消極的なオブジェクト合成的なアレを挟みます.

function fill(base, ext) {
    var k;
    for (k in ext) {
        if (ext.hasOwnProperty(k)) {
            k in base || (base[k] = ext[k]);
        }
    }
}

function Hogehoge() { }

fill(Hogehoge.prototype, {
	prop   : 123,
	method : function() {}
});

console.log(new Hogehoge().constructor.name);
// -> Hogehoge

見栄えもすっきり〜.


Author

ahomuAyumu Sato

overflow, Inc.VPoE

東京資本で生きる名古屋の鳥類

Web 技術、組織開発、趣味など雑多なブログ。技術の話題は zenn にも分散して投稿しています。

Bio: aho.mu
X: @ahomu
Zenn: ahomu
GitHub: ahomu

Related

Latest

Archives

Tags

Search