Using onMissingMethod cannot access object variables

In CF10, I want to access the Test Test object using the onMissingMethod function in the TestHelper object, but I get an error.

Test.cfc

component { public Any function init(){ instance = { x = 1 }; return this; } public numeric function getX(){ return instance.x; } } 

TestHelper.cfc

 component { public Any function init( ){ variables.testObj = new Test(); return this; } public any function onMissingMethod( required string missingMethodName, required struct missingMethodArguments ){ var func = variables.testObj[ arguments.missingMethodName ]; return func( argumentCollection = arguments.missingMethodArguments ); } } 

Object call

 obj = new TestHelper(); writeOutput( obj.getX() ); //Element INSTANCE.X is undefined in VARIABLES 

In CF10, this gives me the error that the X element is undefined. It does not seem to recognize the instance of the variable. I can explicitly define the getX function in TestHelper, but I was hoping I could use the onMissingMethod function.

I do not understand how it is supposed to work on MissingMethod here? FWIW, the code works in Railo.

+5
source share
1 answer

If I understand your problem, I am surprised that this code works on Railo. I do not think it should be.

The problem with this code is:

 var func = variables.testObj[ arguments.missingMethodName ]; return func( argumentCollection = arguments.missingMethodArguments ); 

Here you pull the getX() function from variables.testObj and run it in the context of your TestHelper instance. And this object does not have `variables.x. Hence the error.

You need to put the func link in variables.testObj , and not get getX out of it. So like this:

 var variables.testObj.func = variables.testObj[ arguments.missingMethodName ]; return variables.testObj.func( argumentCollection = arguments.missingMethodArguments ); 

So you are using func() (your proxy for getX() ) in the correct context, so it will see variabales.x.

Given this situation, this method should not work on Railo (based on the information you provided us with all the necessary information, one way or another).

+2
source

All Articles