范围:本地与 Var [英] Scoping: Local vs Var
问题描述
我是 CF 新手,所以这可能是一个基本问题.但是我听说由于 CF 中的作用域如何工作,我应该将 local 用于函数内部的对象.但是'var'呢?var 和使用 local 一样吗?
I'm new to CF so this may be a basic question. But I've heard I should use local for objects inside functions due to how scoping works in CF. But what about 'var'? Is var the same as using local?
例如
function MyFunction()
{
local.obj = {};
}
这是否与:
function MyFunction()
{
var obj = {};
}
如果它们不一样,它们之间有什么区别?我应该什么时候使用它们中的任何一个?
If they aren't the same, what is the difference between them? And when should I be using either of them?
推荐答案
它们非常相似,但并不完全相同.两者都只存在于函数内部,但它们的工作方式略有不同.
They are very similar, but not exactly the same. Both only exist inside of a function but they work slightly differently.
var
版本通过所有默认变量范围工作.请参阅 http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec09af4-7fdf.html
The var
version works it way through all the default variable scopes. See http://help.adobe.com/en_US/ColdFusion/9.0/Developing/WSc3ff6d0ea77859461172e0811cbec09af4-7fdf.html
Local 将仅匹配本地范围内的变量.考虑以下
Local will match only a variable in a local scope. Consider the following
<cffunction name="himom">
<cfoutput>
<p><b>try 0:</b> #request_method#</p>
<!--- you might think that the variable does not exist,
but it does because it came from cgi scope --->
</cfoutput>
<cfquery name="myData" datasource="Scorecard3">
SELECT 'This is via query' AS request_method
</cfquery>
<!--- Data is now being loaded into a query --->
<cfoutput query="myData">
<p><b>try 1:</b> #request_method#</p>
</cfoutput>
<!--- This one now came from the query --->
<cfset var request_method = "This is Var">
<!--- We now declare via var --->
<cfoutput query="myData">
<p><b>try 2:</b> #request_method#</p>
</cfoutput>
<!--- the query version disappears and now
the var version takes precedence --->
<cfset local.request_method = "This is local">
<!--- now we declare via local --->
<cfoutput query="myData">
<p><b>try 3:</b> #request_method#</p>
</cfoutput>
<!--- The local method takes precedence --->
<cfoutput>
<p><b>try 4:</b> #request_method#</p>
<!--- in fact it even takes precedence over the var --->
<p><b>try 5:</b> #local.request_method#</p>
<!--- there is no question where this comes from --->
</cfoutput>
</cffunction>
<cfset himom()>
以上结果
尝试 0:获取
尝试 1:这是通过查询
try 1: This is via query
尝试 2:这是 Var
try 2: This is Var
尝试 3:这是本地的
尝试 4:这是本地的
尝试 5:这是本地的
总结
在开发时,您可以使用其中任何一种来确保变量只存在于函数内部,但始终在变量前加上 local
可以确保您的代码被清楚地理解
When developing, you could use either to make sure that variables only exist inside of a function, but always prefixing your variables with local
goes a long way in making sure that your code is clearly understood
这篇关于范围:本地与 Var的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!