as3 - 公共和公共静态之间的区别?

时间:2015-12-13 04:41:00

标签: actionscript-3

所以我听说静态可以使其他类可以访问该类的变量。

但是当你使用公共或公共静态时它会有什么不同?

他们是否都允许其他类访问该类的变量?

1 个答案:

答案 0 :(得分:2)

已经有一个已经接受的答案,不幸的是,几乎每一个点都是完全错误的。我们不能让人们发现这个帖子并被误导得如此糟糕。这个答案将尝试纠正所有这些错误,以备将来参考。

"公众是文件的可见性"。错误。 Public是一个访问修饰符,用于说明如何从外部访问类,成员和方法。提及"文件"这是错的。

"静态允许访问文件的变量,函数等"。错误。 static只是一个访问修饰符,它使变量或方法属于类而不是实例。它对如何访问这些变量/方法没有影响。例如,无法从外部访问静态私有变量。这里再次提到"文件"是错的,在这里无关。

"公开本质上意味着......等等。 。要让那一个滑动。 public是一个访问修饰符,表示可以从外部访问变量/方法。

"静态意味着它可以被其他文件使用"。绝对不。 static的唯一目的是使变量/方法属于一个类而不是一个实例。它对外部类/实例如何访问它没有影响。例如,任何其他类都无法访问静态私有。这里再次使用术语"文件"被滥用,与编码无关。

现在正确答案:

类中使用的public表示属于该类实例的变量/方法。

类中的public static表示属于该类的变量/方法。

例如,在A类中,公共方法名为" instanceMethod"和名为classMethod的公共静态方法,你可以这样访问它们:

var instance:A = new A();
instance.instanceMethod()//calling an instance method
//the "public function instanceMethod belong to instances of A

A.classMethod()// this is a static public method that only the class itself can call
//trying to do instance.classMethod() would throw an error.
//trying to do A.instanceMethod() would throw an error.

编辑:

要回答您的问题,我们必须讨论范围'但这个话题太大了,无法在这里得到解答。我会给你一些快速指导。

术语范围'在所有编程语言中都使用它,它指的是代码中当前引用的对象。在实例方法中,范围是指实例本身。在静态方法内部,范围是类本身。在实例方法中,这个'这个' keyword是隐式的,指的是实例。在静态方法中,没有'这个'可以使用。理论上,您可以创建无限数量的A类实例,并且每个实例都有自己的“实例方法”。打电话。另一方面,所有静态属性/方法对于类是唯一的,并且由于任何给定项目中的所有类都是唯一的,因此它们始终只有一个。

具体示例:Array类。您可以像这样创建一个新数组:

var myarray:Array = [];
//then use the instance method/property
//those method/property are unique to that instance you just created
myarray.push("hello");
//calling 'push' adds 'hello' to the 'myarray' instance only so 'push' is unique to that instance
//Array class defines also some static property like NUMERIC
myarray.sort(Array.NUMERIC);
//that property NUMERIC is unique to the class and since the class is unique too there's only one Array.NUMERIC that can exist.