2

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.

4

1 回答 1

3

以下似乎有效:

function myP = myParent()

    myP.My_Method = @myMethod;

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

运行如下:

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

从另一个函数运行它也很好:

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

测试:

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

取决于你在做什么,这应该足够了。请注意,您创建的每个句柄都是唯一的,因为它包含有关外部范围变量(在父级中提取的变量)的信息:

当您为嵌套函数创建函数句柄时,该句柄不仅存储函数的名称,还存储外部作用域变量的值。

于 2014-01-23T05:04:59.720 回答