![](/img/trans.png)
[英]What is the difference between javascript property and javascript variable?
[英]What's the difference between a 'var' declared variable and 'this' created property in Javascript?
首先使用var
function testCode(some)
{
var something = some;
}
第二個使用這個
function testCode2(some)
{
this.something = some ;
}
在第一個函數中, something
是私有 (本地)變量,這意味着它在函數外部將完全無法訪問; 而在第二個它是一個公共實例變量。 設置變量的上下文將取決於您調用函數的方式:
> 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"
如果這些函數用作函數,則this關鍵字將使變量成為靜態。 如果函數被調用兩次,this.something仍將具有其值,而第一個主題將在函數執行完畢后擦除變量數據。
如果您將它們用作類構造函數,var將定義一個私有變量,這將聲明一個公共變量。
看到這個小提琴: http : //jsfiddle.net/UUFuX/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.