自引用 (self)

4.6 2026-01-27

self表示当前对象,除此之外self还可以实现运行时判断,避免编译阶段报错


extends Node

func _ready():
  # Compile time error, as `my_var` is not defined in the current class or its ancestors.
  print(my_var)
  # Checked at runtime, thus may work for dynamic properties or descendant classes.
  print(self.my_var)

  # Compile time error, as `my_func()` is not defined in the current class or its ancestors.
  my_func()
  # Checked at runtime, thus may work for descendant classes.
  self.my_func()