https://developer.mozilla.org/ja/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor
coffee script で自動生成される__extends関数を読んでいて、FunctionObject.prototype.constructorプロパティってのを知った。
関数オブジェクトの生成時に自動的に用意されるプロパティで、関数オブジェクトそのものへの参照を持っている。
これを利用することでインスタンスから、その作成元である関数オブジェクトを取得することが出来る。
constructorプロパティは書き換え自由なので、自分で上書きしてしまえる。その場合、インスタンスから作成元を判断する材料が無くなる。
// 関数オブジェクトを用意 SampleClass = function(){ console.log("construct!"); }; // constructorプロパティの確認 SampleClass(); // 関数オブジェクトをそのまま実行 SampleClass.prototype.constructor(); // constructorプロパティに同じものを持っていることを確認 console.log(SampleClass === SampleClass.prototype.constructor); // true // インスタンスからconstructorプロパティの確認 sampleInstance = new SampleClass(); sampleInstance.constructor(); console.log(SampleClass === sampleInstance.constructor); // true // constructorプロパティは上書きしてしまえる PrototypeOverwriteClass = function(){ console.log("construct!"); }; PrototypeOverwriteClass.prototype = {}; // prototypeごと上書き // constructorプロパティが取れないことを確認 PrototypeOverwriteClass(); // 関数オブジェクトをそのまま実行 PrototypeOverwriteClass.prototype.constructor(); // constructorプロパティは取れない console.log(PrototypeOverwriteClass === PrototypeOverwriteClass.prototype.constructor); // false // インスタンスからも、constructorプロパティは取れない prototypeOverwriteInstance = new PrototypeOverwriteClass(); prototypeOverwriteInstance.constructor(); console.log(PrototypeOverwriteClass === prototypeOverwriteInstance.constructor); // false
というわけで、prototypeプロパティに新しいオブジェクトを代入する方式でクラスっぽいものを作るのは、よろしくないらしい。
http://liosk.blog103.fc2.com/blog-entry-193.html