简体   繁体   中英

What's the difference between a 'var' declared variable and 'this' created property in Javascript?

first using var

 function testCode(some) 
    {
         var something = some;
    }

the second using this

function testCode2(some) 
{
     this.something = some ;
}

In the first function, something is a private (local) variable, meaning it will be completely inaccessible outside the function; whilst in the second it's a public instance variable. The context on which the variable will be set will depend on how you invoke the function:

> testCode2("foo"); // this will refer to document.window
> something
"foo"

>> var obj = new testCode2("foo"); // this will refer to the new object
>> something
ReferenceError: something is not defined
>> obj.something
"foo"

Reference:

If those functions are used as functions, the this keyword will make the variable static. If the function is called twice, this.something will still have its value while the first subject will erase the variable data once the function has finished executing.

If you are using them as class constructors, var will define a private variable and this will declare a public variable.

See this fiddle: http://jsfiddle.net/UUFuX/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM