Tom
Tom

Reputation: 8180

actionscript 3 How to access 'this' in inline function

I am trying to do something like:

String.prototype.print=function(){trace(??????)}

I can't for the life of me figure out a way to get at the string! Yes I know there are other ways to approach this etc. but...

Upvotes: 2

Views: 324

Answers (2)

kapex
kapex

Reputation: 29969

Not sure what the problem is, using this works fine in anonymous functions.

  String.prototype.print=function():String{return "printed "+this;}         
  var o:Object = "foo";

  trace(o.print()); // traces: printed foo

I just tricked the compiler to use an object, because "foo".print() causes

Error: Call to a possibly undefined method print through a reference with static type String.

Upvotes: 4

gMale
gMale

Reputation: 17895

It looks like you are mixing ActionScript 2 into your ActionScript 3 code. As kapep said, using "this" will work in your example. That is, this is perfectly valid code:

String.prototype.print=function(){trace(this)}

Of course, you are missing a semi-colon but that shouldn't matter:

String.prototype.print=function(){trace(this);} //semi-colon after 'trace(this)'

Depending on your development environment, you might be having trouble viewing trace statements, in general. In Flex Builder, for example, trace statements don't show up at all unless you are in Debug mode. Insert another call to trace to verify that you can see trace statements.

As you said, there are many other ways to approach this, such as extending the String class and adding your "Print" function. If you really can't get this to work, then trying an ActionScript 3 (i.e. Object-Oriented) approach might be your best option.

Upvotes: 0

Related Questions