是的,这是一个初始化问题。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;
}
};
但这只是针对那个特定的例子,因此上面的讨论是关于一般情况的。