2014-12-29 124 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;