これは、JavaScriptの決定的なガイドから直接、JavaScriptで「クラス」またはコンストラクター関数を記述する教科書の標準的な方法です。
function Rectangle(w,h) {
this.width = w;
this.height = h;
}
Rectangle.prototype.area = function() {
return this.width * this.height;
};
ここでぶら下がっているプロトタイプの操作は好きではないのでarea
、コンストラクター内の関数定義をカプセル化する方法を考えようとしていました。私はこれを思いついたが、これはうまくいくとは思っていなかった。
function Rectangle(w,h) {
this.width = w;
this.height = h;
this.constructor.prototype.area = function() {
return this.width * this.height;
};
}
this
関数内の参照は関数自体area
を指している必要があるため、これが機能するとは思っていませんでした。そのため、にアクセスしたり、からアクセスしたりすることはできません。しかし、私はそうすることがわかりました!area
width
height
this
var rect = new Rectangle(2,3);
var area = rect.area(); // great scott! it is 6
さらにいくつかのテストにより、関数this
内の参照がarea
実際にはエリア関数自体ではなく、構築中のオブジェクトへの参照であることが確認されました。
function Rectangle(w,h) {
this.width = w;
this.height = h;
var me = this;
this.constructor.prototype.whatever = function() {
if (this === me) { alert ('this is not what you think');}
};
}
アラートがポップアップし、this
まさに建設中のオブジェクトであることがわかります。では、ここで何が起こっているのでしょうか。なぜ私はそれが期待されないthis
のですか?this