javascript对象文字 - 对象创建

时间:2012-04-28 13:55:53

标签: javascript object literals

我正在尝试创建一个对象,其中一些属性依赖于其他先前定义的属性,同时尝试依赖于对象文字。否则,我试图完成类似下面的代码(这是不正确的):

var mesh = {
            offset   : $('#mesh').offset(),
            position : $('#mesh').position(),
            height   : win.height - this.offset.top - 12,   
            width    : win.width - this.offset.left - 12,   
            limits   : {}
        }

而不是这种东西(有效):

var mesh = {};
        mesh.offset   = $('#mesh').offset();
        mesh.position = $('#mesh').position();
        mesh.height   = win.height - mesh.offset.top - 12;  
        mesh.width    = win.width - mesh.offset.left - 12;
        mesh.limits = {};

所以我的问题很简单:第一块代码实际上有什么问题,如何根据以前定义的代码创建新属性呢?

2 个答案:

答案 0 :(得分:3)

没有名称引用当前构建的对象文字。您需要使用第二种形式,或者在您可以引用的变量中包含值:

var offset = $('#mesh').offset();
var mesh = {
    offset   : offset,
    position : $('#mesh').position(),
    height   : win.height - offset.top - 12,   
    width    : win.width - offset.left - 12,   
    limits   : {}
}

答案 1 :(得分:0)

你可以创建一个构造函数

var Mesh = function(mesh_id){
    var mesh = $(mesh_id);
    this.offset = mesh.offset();
    this.position = mesh.position();
    this.height = win.height - this.offset.top - 12;
    this.width = win.width - offset.left - 12
    this.limits = {}


};

然后像这样使用它

var myMesh = new Mesh('#mesh')

*请注意,此代码假设定义了一些变量win。您可能已将其定义为var win = $(window)

相关问题