我已经在互联网上上下搜索过,即使是对“this”参考的最轻微提及,也没有发现任何东西!!!似乎根本没有人谈论“这个”。我是一位经验丰富的 c++ 程序员,所以我非常熟悉“this”指针/引用的概念。我的问题是 as3 类中的“this”引用到底是什么?尝试编辑它会引发编译器错误。将它分配给另一个类实例似乎复制了“this”“指向”的内容。我所有试图识别它的尝试都表明它与普通的变量类实例无法区分。我的最终目标是将一个类实例指向一个不同的实例,我一直在尝试确定是否可以使用“this”来简化流程。谢谢!
3 回答
The short answer is: No. You won't be able to re-use this
to point to a different instance of the same class.
The this
keyword in AS3 behaves the same way it would in C#: when used inside of a class, it always references the current instance of the object.
public class Cat
{
var name:String = "";
public function getName():String
{
return this.name;
}
public function setName(name:String):void
{
this.name = name;
}
}
var joe:Cat = new Cat();
joe.setName("Joe"); //joe.getName() will return "Joe"
var john:Cat = new Cat();
john.setName("John"); //john.getName() will return "John"
这是对类的实例的引用。这实际上是为了方便和清晰——即它允许轻松访问代码提示并明确说明您尝试访问的属性/方法。它是一个保留字,因此您不能将其用于其他目的。
对于采用与类属性同名的参数的方法,它可能非常方便,例如:
package
{
public class MyClass
{
private var stuff:String;
public function MyClass()
{
}
public function setStuff(stuff:String):void
{
this.stuff = stuff;
}
}
}
this.stuff 指的是实例属性,而 stuff 指的是已传入的方法参数。如果没有 this,您将对 stuff 的引用不明确,编译器将不知道您要将类属性设置为参数。
package
{
public class MyClass
{
private var stuff:String;
public function MyClass()
{
}
public function setStuff(stuff:String):void
{
stuff = stuff; //NO this KEYWORD!
}
}
}
只需将参数内容设置为自身,就不会发生任何事情。
许多人认为使用它会产生杂乱丑陋的代码。就我个人而言,我经常使用它,但这取决于个人品味和您的团队/项目已同意的约定。
您不能将其重新分配给其他班级。
A quick google gives me these :
http://www.adobe.com/support/flash/action_scripts/event_methods/event_methods05.html
http://www.daveoncode.com/2009/01/07/we-should-always-use-actionscripts-this-keyword/
It just refers to the current instance of the object that the method is on.