Java
Script is a region variable that can use eval to dynamically access scope chain.
As follows:
- VaR OBJ = {};
- (Function (OBJ ){
- VaR var3 = "Varia
Ble 3 ";
- (Function (OBJ ){
- VaR var2 = "variable 2 ";
- (Function (OBJ ){
- VaR var1 = "variable 1 ";
- OBJ. getvar = function (varname ){
- Return eval (varname );
- }
- OBJ. setvar = function (varname, value ){
- Return eval (varname + "= value ");
- }
- }) (OBJ );
- }) (OBJ );
- }) (OBJ );
- Console. Log (obj. getvar ("var2"); // variable 2
- OBJ. setvar ("var2" ,{ ID: 123 })
- Console. Log (obj. getvar ("var2"). Id); // 123
Copy code
Eval function removed after the revised version of ActionScript 3.0
Is it because of this that the access zone variable cannot be dynamically evaluated?
I thought so before.
However, I recently saw articles related to scope chain.
Combined with the as3 namespace syntax learned in the past
I suddenly had other ideas, so I started to test it ~
After the test, a new discovery was made.
Originally, we could use internal namespace to dynamically access the regional variables of scope chain! 』
The namespace built in as3 syntax mainly includes as3, public, protected, private, and internal...
ActionScript language and syntax-packages and namespaces
ActionScript language and syntax-kit and namespace
The key is to use the internal namespace.
File
You can access the namespace at the package level.
But it can also be used to access the regional variables of the scope chain.
The following is a simple demo:
- Package {
- /**
- * Dynamic access to scope variable through the internal namespace
- */
- Import flash
. Display. Sprite;
- [SWF (width = "300", Height = "200")]
- Public class scopetest01 extends sprite {
- Public Function scopetest01 (){
- VaR OBJ: Object = {};
- (Function (OBJ: Object): void {
- VaR var1: String = "variable 1 ";
- VaR var2: String = "variable 2 ";
- OBJ. getvar = function (Name: string ):*{
- Return internal: [name];
- };
- OBJ. setvar = function (Name: String, value :*):*{
- Return internal: [name] = value;
- };
- }) (OBJ );
- Trace (obj. getvar ("var1"); // variable 1
- OBJ. setvar ("var1", "hello ");
- Trace (obj. getvar ("var1"); // hello
- }
- }
- }
- // Ticore's blog-http://ticore.blogspot.com/
Copy code
Amazing!
After Eval is removed, as3 uses the dynamic evaluation capability of the loss and internal namespace to cleverly retrieve the loss.
As3 uses with and proxy to selectively replace scope Variables
ActionScript "with" Block scope Masking Effect
ActionScript 3.0-function Closure
As 3.0 simulates multi-layer block scope using anonymous Functions