Kokodoko
Kokodoko

Reputation: 28128

Can't extend String prototype?

I am trying to extend the String class in Actionscript 3. My goal is to add tags around a string automatically.

Code:

String.prototype.addTags = function(t1:String, t2:String) : String {
    return t1 + this + t2;
}

And then calling the function:

var str:String = "hello";
str.addTags("<b>", "</b>");


// expected output: <b>hello</b>
trace(str);

This generates the following error:

1061: Call to a possibly undefined method addTags through a reference with static type String.

Upvotes: 2

Views: 255

Answers (3)

Aaron Beall
Aaron Beall

Reputation: 52133

I agree with some of the other answers that consider this a "bad idea". However, just to answer your question, the problem with your original code is simply that you weren't doing anything with the returned value of addTags(). This should work:

String.prototype.addTags = function(t1:String, t2:String):String {
    return t1 + this + t2;
}

var str:String = "hello";
str = str.addTags("<b>", "</b>");

trace(str); // <b>hello</b>

Although in "strict mode" you'll get a compile error on str.addTags() because addTags() is not a known method of String by the compiler. You can get around this by using a dynamic reference or casting to Object which is dynamic:

str = Object(str).addTags("<b>", "</b>");

The Array class is already dynamic, so that's why you don't get this compile error when using methods added to the array prototype.

Again, I agree with others that there are "better" ways to do this. (ie ways that fit AS3's language design better.)

Upvotes: 1

akmozo
akmozo

Reputation: 9839

If you want to do that using "prototype", you can upcast your string (or number if you want) to an Object like this :

Object.prototype.addTags = function(t1:String, t2:String):String {
    return t1 + this + t2;
}

var str:String = 'hello';
    str = Object(str).addTags('<b>', '</b>');

trace(str);                                     // gives : <b>hello</b>

trace(Object('world').addTags('<u>', '</u>'));  // gives : <u>world</u>

trace(Object(2015).addTags('<p>', '</p>'));     // gives : <p>2015</p>

Hope that can help.

Upvotes: 0

Crabar
Crabar

Reputation: 1857

This is a bad idea. And you cannot extend primitive types. Better will be if you create class-utility to do whatever you want. For example:

package {
    public class StringUtil {
        public static function addTags(value:String, leftTag:String, rightTag:String):String {
            return leftTag + value + rightTag;
        }
    }
}

P.S. It's just example. There are many different ways to implement what you want.

Upvotes: 0

Related Questions