动作3:谁能给我解释一下静态变量和方法的概念?给我、谁能、变量、静态

2023-09-08 12:11:17 作者:骑着羊儿去放狼ゞ

我学AS3,并感到有点困惑,什么是静态变量或方法呢,还是有什么不同的方法或变量不包含此关键字。这应该是很简单的回答,我想。

I'm learning AS3, and am a bit confused as to what a static variable or method does, or how it differs from a method or variable without this keyword. This should be simple enough to answer, I think.

推荐答案

静态指定变量,常量或方法属于类而不是类的实例。 静态变量,函数或常量可以在不创建类,即 SomeClass.staticVar 的实例进行访问。他们没有任何的子类,只有继承类(无接口)可以有静态成员。 A 静态功能无法访问任何非静态成员(变量,常量或功能)之类的,你不能使用静态函数内部。下面是一个简单的例子。

static specifies that a variable, constant or method belongs to the class instead of the instances of the class. static variable, function or constant can be accessed without creating an instance of the class i.e SomeClass.staticVar. They are not inherited by any subclass and only classes (no interfaces) can have static members. A static function can not access any non-static members (variables, constants or functions) of the class and you can not use this or super inside a static function. Here is a simple example.

public class SomeClass 
{
  private var s:String;
  public static constant i:Number;
  public static var j:Number = 10;

  public static function getJ():Number 
  {
    return SomeClass.j;
  }
  public static function getSomeString():String 
  {
    return "someString";
  }
}

在TestStatic,静态变量和函数可以在不产生SomeClass的实例访问。

In the TestStatic, static variables and functions can be accessed without creating an instance of SomeClass.

public class TestStaic 
{
  public function TestStaic():void 
  {
    trace(SomeClass.j);  // prints 10
    trace(SomeClass.getSomeString());  //prints "someString"
    SomeClass.j++; 
    trace(SomeClass.j);  //prints 11
  }
}