【问题标题】:ActionScript problem with prototype and static type variables原型和静态类型变量的 ActionScript 问题
【发布时间】:2009-02-19 12:42:35
【问题描述】:

我正在开发一个 Flash(Flash 9、AS3)来连接到服务器并将数据发送/接收/解析到 JavaScript/HTML 聊天。 我有这样的结构:

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());
        }
    }
}

当我编译它时,我得到这个错误:

1061: 调用可能未定义的 通过引用的方法 escapeHtml 使用静态类型字符串。

如果我删除:String,一切正常,但我必须检查str 是否为字符串以及是否未定义等等。

我的代码中有很多这样的函数,其中许多接收用户输入的数据,所以我认为删除 :String 并对每个函数进行多次检查并不是最好的方法。

我怎样才能做到这一点?

【问题讨论】:

    标签: actionscript-3 prototype


    【解决方案1】:

    然后只定义函数:

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

    在你的课堂上。

    并称它为:

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

    :)

    【讨论】:

    • 这可以解决问题,但是当您拥有 function(function2(function3(str))) 时,它就很难看。可能那是我的糟糕编码。
    【解决方案2】:

    由于编译器处于严格模式,您会收到错误消息。 如果你想保持严格模式,你可以试试这个:

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

    【讨论】:

    • 实际上就是这样。我不记得我将它置于严格模式。
    【解决方案3】:

    原型实际上是遗留物。

    您应该扩展 String 类并使用您的自定义类

    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;
            }
        }
    }
    

    【讨论】:

    • 其实有问题。我实际上无法扩展 String 类(“1016:基类是最终的。”),所以我松散了拆分、替换等方法,我需要它们。
    猜你喜欢
    • 1970-01-01
    • 2017-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-07
    • 2011-08-25
    • 2013-02-08
    • 2012-01-02
    相关资源
    最近更新 更多