将属性作为参数传递,同时设置同一对象的其他属性

Passing properties as arguments while setting other properties of same object

本文关键字:属性 对象 其他 设置 参数传递      更新时间:2023-09-26

我正在使用Raphael.js制作一个小JS游戏。这是我在JS中的第一个大项目,所以我不熟悉所有的设计模式等。我要创建一个对象来表示移动计时器。从"litCircle"行开始,我得到错误:

Uncaught TypeError: Cannot read property '0' of undefined

c是我的拉斐尔对象。有没有什么我不知道的,你不能使用你目前在函数调用中定义的对象的属性,你正在使用它来帮助设置对象的其他属性的值?

var moveTimer = {
  mtScaler : 15,
  all : c.set(),
  RS : [1*this.mtScaler,3*this.mtScaler,4*this.mtScaler],
  litCircle : c.circle(200,37,this.RS[0]),
  midCircle : c.circle(200,37,this.RS[1]).attr({
    "stroke-dasharray": "- "
  }),
  bigCircle : c.circle(200,37,this.RS[2]).attr({
    "stroke-dasharray":". "}),
  orangeOne : c.circle(200, 37,this.RS[0]).attr({
    "stroke-width": 2,
    "stroke": COLOR_DICT["orange"],
  }),
  turnCounter : c.text(200,38,0),
  orangeAnim :
    Raphael.animation({
      "50%": { r: this.RS[2] },
      "100%": {  r: this.RS[0] }
    }, 3000),
  finish : function(){
    this.all.push(this.litCircle, this.midCircle, this.bigCircle,
      this.orangeOne, this.turnCounter);
    this.all.transform("t250,230");
  }
}

RS在你调用它的时候仍然是被定义的,定义一些定义之外的变量并利用它们。

的例子:

var scaler, rs;
scaler = 15;
rs = [1*tscaler,3*tscaler,4*scaler];
var moveTimer = {
  mtScaler : scaler,
  all : c.set(),
  RS : rs,
  litCircle : c.circle(200,37,rs[0]),
  midCircle : c.circle(200,37,rs[1]).attr({
    "stroke-dasharray": "- "
  }),
  bigCircle : c.circle(200,37,this.RS[2]).attr({
    "stroke-dasharray":". "}),
  orangeOne : c.circle(200, 37,this.RS[0]).attr({
    "stroke-width": 2,
    "stroke": COLOR_DICT["orange"],
  }),
  turnCounter : c.text(200,38,0),
  orangeAnim :
    Raphael.animation({
      "50%": { r: this.RS[2] },
      "100%": {  r: this.RS[0] }
    }, 3000),
  finish : function(){
    this.all.push(this.litCircle, this.midCircle, this.bigCircle,
      this.orangeOne, this.turnCounter);
    this.all.transform("t250,230");
  }
}

这可能不是100%,因为我不能确认代码,但这是一个起点。

thislitCircle : c.circle(200,37,this.RS[0])表示调用者,Window对象,而不是您定义的moveTimer

显然,Window对象没有RS属性。