3

I'm developing a flash (Flash 9, AS3) to connect to a server and send/receive/parse data to a chat on JavaScript/HTML. I have a structure like this:

package {
    public class myClass {
        String.prototype.escapeHtml = function() {
            var str = this.replace(/&/g, "&");
            str = str.replace(/</g, "&lt;");
            str = str.replace(/>/g, "&gt;");
            return str;
        }

        function writeToBrowser(str:String) {
            ExternalInterface.call("textWrite",str.escapeHtml());
        }
    }
}

When I compile it, I get this error:

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

If I remove the :String, it all works fine, but then I'd have to check if str is a String and if it's not undefined and so on.

I have many functions like this on my code, many of them receive user-entered data, so I think that removing the :String and doing many checks on every function isn't the best approach.

How can I make this right?

3 Answers 3

3

Then just define the function:

public function escapeHtml( str : String ) : String
{
    var str = this.replace(/&/g, "&amp;");
    str = str.replace(/</g, "&lt;");
    str = str.replace(/>/g, "&gt;");

    return str;
}

in your class.

And call it:

public function writeToBrowser( str : String )
{
    ExternalInterface.call( "textWrite", escapeHtml( str ) );
}

:)

Sign up to request clarification or add additional context in comments.

1 Comment

That would solve the problem, but when you have function(function2(function3(str))) it's just ugly. Probably that's my bad coding.
2

you get an error because the compiler is in strict mode. if you want to stay in strict mode you can try this:

ExternalInterface.call("textWrite",str["escapeHtml"]() );

1 Comment

That was actually it. I didn't remember I'd put it in strict mode.
1

Prototype is actually legacy.

You should extend the String class and use your custom class

package {
    public class myClass {

        public function writeToBrowser(str:CustomString) {
                ExternalInterface.call("textWrite",str.escapeHtml());
        }
    }
    public class CustomString {

        public function escapeHtml():String {
                var str = this.replace(/&/g, "&amp;");
                str = str.replace(/</g, "&lt;");
                str = str.replace(/>/g, "&gt;");
                return str;
        }
    }
}

1 Comment

Actually, there's a problem. I can't actually extend the String class ("1016: Base class is final."), so I loose methods like split, replace, etc. and I need them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.