2014-12-29 123 views
1

我想知道下面的行是什麼樣的語法被調用。多個變量分配給Javascript中的一個變量?

var that = {}, first, last; 

注:我發現本網站上關於這個問題的帖子,但他們說[]已經圍繞變量被添加在右手邊,使其數組。但下面的代碼確實有效。

代碼:

var LinkedList = function(e){ 

    var that = {}, first, last; 

    that.push = function(value){ 
    var node = new Node(value); 
    if(first == null){ 
     first = last = node; 
    }else{ 
     last.next = node; 
     last = node; 
    } 
    }; 

    that.pop = function(){ 
    var value = first; 
    first = first.next; 
    return value; 
    }; 

    that.remove = function(index) { 
    var i = 0; 
    var current = first, previous; 
    if(index === 0){ 
     //handle special case - first node 
     first = current.next; 
    }else{ 
     while(i++ < index){ 
     //set previous to first node 
     previous = current; 
     //set current to the next one 
     current = current.next 
     } 
     //skip to the next node 
     previous.next = current.next; 
    } 
    return current.value; 
    }; 

    var Node = function(value){ 
    this.value = value; 
    var next = {}; 
    }; 

    return that; 
}; 

回答

3
var that = {}, first, last; 

類似於

var that = {}; 
var first; 
var last; 

我們正在與空對象初始化that,而firstlast是未初始化的。所以他們將有默認值undefined

JavaScript爲單個語句中聲明的變量從左到右分配值。因此,下面

var that = {}, first, last = that; 
console.log(that, first, last); 

將打印

{} undefined {} 

其中作爲

var that = last, first, last = 1; 
console.log(that, first, last); 

將打印

undefined undefined 1 

因爲,在時間that分配lastlast的值尚未定義。所以,這將是undefined。這就是爲什麼thatundefined

1

這只是創建多個變量的簡寫方式。如果寫成這可能是更明確:

var that = {}, 
    first, 
    last; 

,等同於:

var that = {}; 
var first; 
var last;