AS3检查变量是否为String输出MouseEvent信息

时间:2016-01-27 10:54:56

标签: actionscript-3

更新:我找到了使用不同代码的解决方法。我正在离开这个问题,因为有人想回答为什么会这样,也许它可以帮助其他人。感谢

我试图检查一个变量是否是一个字符串,在这种情况下,如果它在字符串中有一个url。但是代码正在执行,在trace语句中我得到了这个:

if (theWebsite is String)
trace(theWebsite);

输出: [MouseEvent type =“click”bubbles = true cancelable = false eventPhase = 3 localX = 2259.8671875 localY = 2485.85205078125 stageX = 1003.25 stageY = 71 relatedObject = null ctrlKey = false altKey = false shiftKey = false buttonDown = false delta = 0 commandKey = false controlKey = false clickCount = 0] 主舞台? [对象Main_Activate]和网站? [MouseEvent type =“click”bubbles = true cancelable = false eventPhase = 3 localX = 2259.8671875 localY = 2485.85205078125 stageX = 1003.25 stageY = 71 relatedObject = null ctrlKey = false altKey = false shiftKey = false buttonDown = false delta = 0 commandKey = false controlKey = false clickCount = 0]

以下是创建此变量的代码。

1

MenuScreen.One_btn.addEventListener(MouseEvent.CLICK, webViewButton("http://www.MyWebsite.com"));

2

public function webViewButton(theWebsite:String):Function  {
            trace("made it here: " + theWebsite); /// output: www.MyWebsite.com
            return function(e:MouseEvent):void {
                trace("made it here too: " + theWebsite); //output: www.MyWebsite.com
            removeMenuScreen(theWebsite);
            }
        }

3

public function removeMenuScreen(theWebsite:String = null, e: Event = null) {

            if (theWebsite is String) {
                trace("But did I make it here? " + theWebsite);
                // OUTPUTS all the above code mentioned earlier. 
            }

我正在将该功能用于其他事情,这就是为什么它的设置方式。 我如何解决此问题,只有在定义的字符串中才执行该代码?感谢您提供的任何提示。

1 个答案:

答案 0 :(得分:1)

您发布的代码会生成您发布的输出。

生成" addEventListener(MouseEvent.CLICK, removeMenuScreen)"如果您有类似MouseEvent的内容,则输出。为什么?由于removeMenuScreen处理程序的第一个参数theWebsite的类型为String,因此theWebsite将被强制转换为其字符串值。

所以,回答你的问题:只有当null是一个字符串时才会执行。并且它永远是一个字符串,或public function removeMenuScreen(theWebsite:* = null) { if (theWebsite is String) { trace("But did I make it here? " + theWebsite); } else if (theWebsite is MouseEvent) { trace("Or did I make it here?", theWebsite) } } ,否则,如果不能强制转换为字符串,则会引发运行时错误。

如果要避免运行时强制,请将参数设为无类型:

{{1}}

我不建议你走这条路,因为它增加了很多不清晰,导致错误和调试困难。