문제

Is there a way to create a function handle to a nested function that includes the parent function in the function handle?

As an example, say I have:

function myP = myParent()

    myP.My_Method = myMethod;

    function myMethod()
        disp "hello world"
    end
end

In another file, I could call the method by doing something like:

myP = myParent();
myP.My_Method();

But, if I have another function that takes function handles as a parameter and then calls the function, how do I pass in the function handle to myMethod in this case, since this new function can't create a myParent variable.

도움이 되었습니까?

해결책

The following seems to work:

function myP = myParent()

    myP.My_Method = @myMethod;

    function myMethod()
        s=dbstack;
        fprintf('Hello from %s!\n',s(1).name);
    end
end

Running it as follows:

>> myP = myParent()
myP = 
    My_Method: @myParent/myMethod
>> feval(myP.My_Method)
Hello from myParent/myMethod!
>> myP.My_Method()
Hello from myParent/myMethod!

It is also fine to run it from another function:

% newfun.m
function newfun(hfun)
feval(hfun)

Test:

>> newfun(myP.My_Method)
Hello from myParent/myMethod!

Depending on what you are doing, this should be enough. Note that each handle you create is unique since it contains information about externally scoped variables (variables pulled in the parent):

When you create a function handle for a nested function, that handle stores not only the name of the function, but also the values of externally scoped variables.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top