When to var scope your variables in ColdFusion components?

一世执手 提交于 2019-12-10 14:58:34

问题


(a) What cases should you var scope variables and (b) what cases should you not var scope in a ColdFusion components?


回答1:


You should var scope your variables when you're implementing a function inside a CFC that is shared across multiple requests (i.e. Singleton, Service CFC's in Application scope)

You don't need to (yet still highly recommended to) var scope your variables if the CFC is instantiated every time, AND your method is not calling another method in the same CFC that may access the vars you've defined in the caller method. Such as a remote method that you called directly through web service or ajax, which doesn't call other methods that make use of vars you didn't var scope, or Controller in CFWheels.

"You should always define function-local variables using the var keyword." per CFC variables and scope doc http://livedocs.adobe.com/coldfusion/8/htmldocs/help.html?content=buildingComponents_29.html




回答2:


You should var scope your variables any time you do not want the value of that variable to be affected by a) other requests accessing the same instance, or b) other methods within the same instance.

Henry is a great guy, but his statement that "You don't need to var scope your variables if the CFC is instantiated every time." is incorrect. :) [EDIT: Henry has since edited his answer] I wrote an example that illustrates this point in this blog entry:

http://daveshuck.com/2006/11/28/thread-safety-example-var-scope-your-loop-index-in-coldfusion-cfcs/

You can see that I created an infinite loop by counting up in one function and counting down in another. In this case it doesn't matter whether it is a singleton or multiple users requesting the same instance, but in a single request one function is overwriting the value in another function.




回答3:


I var scope any variable that is not a global or member of the component. The last thing you want to be doing is creating or overwriting globals in the variables scope




回答4:


We scope all vars in a function so that they stay local to that function only. As for the component, you can use variables or this scopes to make the variables available to any function in the component. The "this" scope will also make the variables directly available to the calling program if you set the access correctly.



来源:https://stackoverflow.com/questions/5340722/when-to-var-scope-your-variables-in-coldfusion-components

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!