[英]AS3 adding a function to an existing object dynamically
var s={};
s.WHEN={}
Why does this work: 为什么这样做:
s.WHEN.foo=5;
but this not: 但这不是:
s.WHEN['info']=function(){trace('do something');}
? ?
after I run both these lines my s.WHEN Object has only foo:5 and is missing info:function 在运行这两行之后,我的s.WHEN对象只有foo:5并且缺少info:function
I use this function to see from flash through the console in the browser... 我使用此功能通过浏览器中的控制台从Flash中查看...
var console:Object={
log:function(_){ExternalInterface.call("window.console.log",_);},
dir:function(_){ExternalInterface.call("window.console.dir",_);}
}
Then if I do (in flash): 然后,如果我这样做(在闪光灯中):
console.log(s.WHEN);
I see: 我懂了:
Object
> foo: 5
> __proto__: Object
But if I do: 但是如果我这样做:
console.log(s.WHEN['info']);
I see: 我懂了:
function
Why is it there but not as part my s.WHEN object?? 为什么它在那里但不属于我的s.WHEN对象?
if you try 如果你试试
trace( console.log );
You will also see function
because you are referencing a function and not a function call. 您还将看到function
因为您引用的是函数而不是函数调用。
So use : 因此使用:
console.log( s.WHEN() );
But you will see nothing (well, you will have a trace in Flash console) because the function referenced by WHEN return nothing. 但是您什么也看不到(嗯,在Flash控制台中将有一个跟踪),因为WHEN引用的函数什么也不返回。
s.WHEN[ 'info' ] = function(){ return 'do something' };
console.log( s.WHEN() ); // <-- Note the bracket after WHEN
And it will work. 它将起作用。
But as Gio said, you should use OOP and not anonymous Object/Function, it makes life easy and debug won't be a pain. 但是正如Gio所说,您应该使用OOP而不是匿名的Object / Function,它使工作变得轻松,并且调试将不会很麻烦。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.