はい、初期化の問題です。オブジェクトを使用している時点でオブジェクトをthis
参照していません。SizeManager
(オブジェクト初期化子は の値を変更しませんthis
。)this
は、関数の呼び出し方法によって設定され、その関数呼び出し全体で同じ値を持ちます。そこでは関数を呼び出していないためthis
、そのコードの開始前に持っていた値は何でもあります。
(これの最後にある特定の例から何かを指摘しましたratio
が、最初に、あなたが提起した一般的なケースのいくつかのオプションを見てみましょう。)
ダニエルratio
は、幅を変えたいと思っていることに気付いていないように見えることを除いて、関数を作成する上であなたに良い操縦を与えました. または、width
とheight
が変わらない場合は、後で計算します。
var SizeManager = {
width : 800,
height : 600,
resize : function (newWidth) {
this.width = newWidth;
this.height = newWidth / this.ratio;
}
};
SizeManager.ratio = SizeManager.width / SizeManager.height;
(補足: でthis.
参照しているプロパティに追加しましたresize
。元のものにはありませんでしたが、必須です。それらがないと、暗黙のグローバルの恐怖に対処することになり、これは悪いことです( tm) .)
もちろん、そのすべてをファクトリにカプセル化することもできます。
function makeSizeManager(width, height) {
return {
width : width,
height : height,
ratio : width / height,
resize : function (newWidth) {
this.width = newWidth;
this.height = newWidth / this.ratio;
}
};
}
var SizeManager = makeSizeManager(800, 600);
resize
...しかし、それを実際のコンストラクター関数にすることもできるので、多くの重複する (ただし同一の)関数を作成しないでください。
function SizeManager(width, height) {
this.width = width;
this.height = height;
this.ratio = width / height;
}
SizeManager.prototype.resize = function (newWidth) {
this.width = newWidth;
this.height = newWidth / this.ratio;
};
var aSizeManagerInstance = new SizeManager(800, 600);
(この最後の名前を少し変更したことに注意してください。)
最後の最後の注意として、あなたの特定の例では、実際にはratio
まったく保存する必要はありません。これを行うことができます:
var SizeManager = {
width : 800,
height : 600,
resize : function (newWidth) {
var ratio = this.width / this.height;
this.width = newWidth;
this.height = newWidth / ratio;
}
};
しかし、それはその特定の例のためだけであるため、上記の議論は一般的なケースについて話している.