Project1

标题: self.变量的self的意思 [打印本页]

作者: 鲸梦鲸    时间: 2018-9-23 11:35
标题: self.变量的self的意思
按照文档改写计时器时遇到了这个问题。

class Sprite_Timer
  alias jingmo_create_bitmap create_bitmap
  alias jingmo_update_position update_position
  def create_bitmap
    jingmo_create_bitmap
    self.bitmap = Bitmap.new(200,50)
    self.bitmap.font.size=20
    self.bitmap.font.color.set(50,62,78)
  end
  def update_position
    x=0
  end
end
不加self.的话那bitmap就还是未改写之前的bitmap。
而update_position中x虽然没有加self.却没问题。
下面是原来的方法。

def create_bitmap
    self.bitmap = Bitmap.new(96, 48)
    self.bitmap.font.size = 32
    self.bitmap.font.color.set(255, 255, 255)
  end


def update_position
    self.x = Graphics.width - self.bitmap.width
    self.y = 0
    self.z = 200
  end
作者: 余音·魔眼    时间: 2018-9-23 19:01
self是当前对象的意思,也就是存储Sprite_Timer这个类的实例变量
作者: 鲸梦鲸    时间: 2018-9-24 14:57
啊,确定了这个的话重新分析一遍我好像知道了。
给create_bitmap命别名后我在新的方法引用了一遍原来的方法,而原来的方法一开始已经有了self.bitmap变量,所以我在新的方法中其实是给self.bitmap重新赋值了,不加self.实际上是定义了另一个bitmap,所以没用。




欢迎光临 Project1 (https://rpg.blue/) Powered by Discuz! X3.1