Skip to main content
Inspiring
February 27, 2009
Question

Difference between this,var and variables

  • February 27, 2009
  • 4 replies
  • 492 views
Hi all,
Can you give in simple English "this","var" and "variables" differ and their purposes?

The docs in google are confusing,Thank you all.
    This topic has been closed for replies.

    4 replies

    emmim44Author
    Inspiring
    February 27, 2009
    Thank you Tariq as well
    Participating Frequently
    February 27, 2009
    Consider this:

    X.CFC
    ==========================
    <cfcomponent>
    ___<cfset this.foo = "foo"> <--- Public
    ___<cfset Variables.bar = "bar"> <--- Private

    ___<cffunction name="tryme">
    _____<cfoutput>
    ______#this.foo#<P>
    ______#Variables.bar#
    _____</cfoutput>
    ___</cffunction>
    </cfcomponent>
    ==========================

    Example 1: You can do this:
    <cfobject type="component" component="x" name="xObj">
    <cfoutput>#xObj.tryme()#</cfoutput>

    It'll output "foo bar"

    Example 2: You can't do this:
    <cfobject type="component" component="x" name="xObj">
    <cfoutput> #xObj.foo# #xObj.bar#</cfoutput>

    It'll get upset on the #xObj.bar# part because it's private - meaning only the CFC can access and manipulate a Variables variable inside it's CFC.

    However #xObj.foo# works because it's public, the CFC can access and manipulate it's own this variable, and anything outside of it can too.
    emmim44Author
    Inspiring
    February 27, 2009
    Thank you Dan...
    Inspiring
    February 27, 2009
    var is a keyword. It's used inside a function and ensures that the variable remains local to the function.

    this and variables are scopes.

    The variables scope can be used anywhere. They are generally set by code. For example,
    <cfset x = 1>
    creates a variable in the variables scope. Other scopes people often encounter are form, url, and cgi.

    The this scope can only be used in a cfc (I think). It can be set either inside or outside a function. Once it is set, it's available to all the functions in that cfc.

    Similarly, if you do this
    <cfset x = 1>
    in a cfc but not inside a function, that variable will also be available to all the functions. One difference between doing this, and using the this scope, is that variables in the this scope can have there values changed by the calling template.