bon*_*nfo 8 javascript constructor object-literal
我正在使用object literal来创建一个带有方法的对象.
这是一个简单的例子.
var SizeManager = {
width : 800,
height : 600,
ratio : this.width / this.height,
resize : function (newWidth) {
width = newWidth;
height = newWidth / ratio;
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是SizeManager.ratio返回" NaN ".我很确定这是一个初始化问题.
有没有办法获得正确的比率值?
有没有办法为对象文字分配一个costructor或初始化器?
是定义构造函数objcet的唯一方法吗?
编辑:当然,SizeManager理想情况下是一个单例(只有一个对象),这就是我使用对象文字的方式.
T.J*_*der 24
是的,这是一个初始化问题.在您使用它时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;
Run Code Online (Sandbox Code Playgroud)
(旁注:我已经添加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);
Run Code Online (Sandbox Code Playgroud)
...但是你可以将它作为一个实际的构造函数,这样你就不会创建大量重复(但相同)的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);
Run Code Online (Sandbox Code Playgroud)
(注意我在最后一个上改了一些名字.)
最后一个最后一点:在您的具体示例中,您实际上根本不需要存储ratio
,您可以这样做:
var SizeManager = {
width : 800,
height : 600,
resize : function (newWidth) {
var ratio = this.width / this.height;
this.width = newWidth;
this.height = newWidth / ratio;
}
};
Run Code Online (Sandbox Code Playgroud)
但这仅仅是针对该具体示例,因此上面的讨论将讨论一般情况.
你的ratio
财产实际上应该是一个方法,如果您想根据修改它改变width
和height
:
var SizeManager = {
width : 800,
height : 600,
ratio : function() {
return this.width / this.height;
},
resize : function (newWidth) {
width = newWidth;
height = newWidth / ratio;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,你可能想参考this.width
和this.height
替代width
和height
在resize
方法.
归档时间: |
|
查看次数: |
8398 次 |
最近记录: |