フィルターのクリア

Scope of variables passed to function handles?

2 ビュー (過去 30 日間)
Dehuan
Dehuan 2014 年 12 月 16 日
コメント済み: Dehuan 2014 年 12 月 16 日
Hi, everyone,
I want to ask about the non-input variables in function handles.
For example, following code returns h(1)=2.
b=1;
h=@(a)a+b;
clear b;
display(sprintf('h(1)=%d', h(1)));
Is this kind of usage safe and correct?
Dehuan

採用された回答

matt dash
matt dash 2014 年 12 月 16 日
As far as i know, yes this is safe and correct. Any non-input variables pass their values to the function at the time the function handle was created. Subsequent changes to or clearing of those variables has no effect on the function.
  2 件のコメント
Adam
Adam 2014 年 12 月 16 日
Yes, this is correct. It is also why passing the handles structure, for example, in a GUIDE-based file to a callback is not a good idea, because a copy of the structure at the exact time the callback is set is hard-coded into the callback, irrespective of when it is called.
Dehuan
Dehuan 2014 年 12 月 16 日
Thanks guys.
This is actually a very neat feature.
It makes dependency-inject and functional programming a lot simpler.

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeInteractive Control and Callbacks についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by