【问题标题】:using this. in javascript object definition使用这个。在 javascript 对象定义中
【发布时间】:2012-07-16 15:21:33
【问题描述】:

所以我是 Javascript 中的对象定义的新手,并且正在尝试编写一个将对象作为练习的程序。我的问题是,当我尝试定义对象时,某些对象属性依赖于对象的其他部分。我不确定这是否被允许,因为在我所有的搜索中我都找不到它的任何例子。

我的问题基本上是这样的:我可以使用先前定义的对象属性来定义该对象吗?最基本的例子是这样的:

var alfred = {
    dogs: 1,
    cats:this.dogs+1,
}

这是允许的吗?如果是这样,这是正确的语法吗?我需要使用“this”的原因。是因为我将新创建的对象推送到对象数组中。我的代码不起作用如下:

obj.push({
    canvas:document.getElementById(canvasName),

    canvasName:"canvas"+objNum,
    image: img,
    width:objWidth,
    height:objHeight,
    centerX:posX,
    centerY:posY,
    speed:speeds,
    hypSquare:Math.sqrt((this.width*this.width)+(this.height*this.height)),
    angleInSquare:Math.atan(this.height/this.width),
    angle:startAngle,
    angleTotal:this.angle+this.angleInSquare,
    offX:(this.hypSquare* Math.cos(this.anglesTotal))/2,
    offY:(this.hypSquare* Math.sin(this.anglesTotal))/2,
    centeredX:this.centerX-this.offX,
    centeredY:this.centerY-this.offY,
})

当我打电话时

console.log(obj[objNum].hypSquare);

(其中 objNum 只是数组中对象的索引)即使我调用也会得到 NaN

 console.log(obj[objNum].width);

我会得到 objWidth 的值。只是语法问题,还是我对对象的理解存在根本缺陷...

提前感谢您的宝贵时间!

艾萨克

【问题讨论】:

    标签: javascript object properties this definition


    【解决方案1】:

    不,你不能那样做。您必须关闭object initializer,然后添加其他属性,例如:

    var alfred = {
        dogs: 1
    };
    alfred.cats = alfred.dogs + 1;
    

    因此,对于您的 obj.push 调用,您必须使用临时变量(如上面的 alfred),您不能只使用内联对象初始化器。

    【讨论】:

    • 太棒了!非常感谢您的建议。我害怕我不得不这样做,但这就是生活......
    【解决方案2】:

    你不能那样做。但是,您可以使用对象构造函数。

    function Person(canvasName, objNum) {
      this.canvas = document.getElementById(canvasName);
    
      this.canvasName = "canvas" + objNum;
      ...
      this.centeredY = this.centerY - this.offY;
    }
    
    obj.push(new Person("alfred", 3));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-10
      • 2012-02-23
      • 2014-10-05
      • 1970-01-01
      • 2021-07-25
      相关资源
      最近更新 更多