本文介绍了作用域:本地与变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是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 版本在所有默认变量范围。请参见

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 is takes presidence --->


    <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 presidence --->




   <cfoutput>
   <p><b>try 4:</b> #request_method#</p>
   <!--- in fact it even takes presidence 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:GET

尝试1:通过查询

尝试2:是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

这篇关于作用域:本地与变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:33