Javascript对象文字:值初始化?

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功能,除了他似乎没有意识到你想要改变宽度.或者,如果widthheight不会改变,只需在之后计算:

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)

但这仅仅是针对该具体示例,因此上面的讨论将讨论一般情况.

  • 如果要将其从对象文字更改为函数,则需要更改指定属性的方式(在第三个代码块中).即.`this.width = width`而不是`this.width:width` (2认同)

Dan*_*uis 5

你的ratio财产实际上应该是一个方法,如果您想根据修改它改变widthheight:

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.widththis.height替代widthheightresize方法.