2015-10-25 45 views
0

我有一個LinkedList類,我想讓該實例的head成員爲私有。我看到我可以如何爲每個實例創建一個密鑰ID,並隱藏LinkedList類的用戶成員。尋找一些其他的方法,使this.head私人讓一個私人會員不使用實例Ids Javascript

function LinkedList() { 
 
    this.head = null; 
 
}; 
 

 
LinkedList.prototype = (function() { 
 
    function reverseAll(current, prev) { 
 
     if (!current.next) { //we have the head 
 
      this.head = current; 
 
      this.head.next = prev; 
 
     } 
 

 
     var next = current.next; 
 
     current.next = prev; 
 

 
     reverseAll(next, current); 
 
    }; 
 

 
    return { 
 
     constructor: LinkedList, 
 

 
     reverse: function() { 
 
      reverseAll(this.head, null); 
 
     }, 
 

 
     head: function() { 
 
      return this.head; 
 
     } 
 
    } 
 
})(); 
 

 
LinkedList.prototype.add = function(value) { 
 
    var node = { 
 
     value: value, 
 
     next: null 
 
    }; 
 

 
    var current; 
 

 
    if (this.head === null) { 
 
     this.head = node; 
 
    } else { 
 
     current = this.head; 
 
     while (current.next) { 
 
      current = current.next; 
 
     } 
 
     current.next = node; 
 
    } 
 

 
    return node; 
 
} 
 

 
LinkedList.prototype.remove = function(node) { 
 
    var current, value = node.value; 
 

 
    if (this.head !== null) { 
 
     if (this.head === node) { 
 
      this.head = this.head.next; 
 
      node.next = null; 
 
      return value; 
 
     } 
 
     //find node if node not head 
 
     current = this.head; 
 
     while (current.next) { 
 
      if (current.next === node) { 
 
       current.next = node.next; 
 
       return value; 
 
      } 
 

 
      current = current.next; 
 
     } 
 
    } 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<script> 
 
$(function() { 
 
    var obj = new LinkedList(); 
 
    
 
    for (var i = 1; i <= 10; i++) { 
 
     obj.add(i); 
 
    } 
 
    
 
    console.log(obj.head); 
 
    obj.head = 'pwned'; 
 
    console.log(obj.head); 
 
}); 
 
</script>

回答

0

唯一我能想到的辦法是某種可憎的是這樣的:

function LinkedList() { 
    let head = null; 
    // Instead of using a prototype, you attach the methods directly to this. 
    // This makes the methods unique per instance, so you can attach privately 
    // scoped variables (like head). 
    this.reverse = function() { 
     // You may use head here. 
    }; 
    this.head = function() { ... }; 
} 

然而,這是高度效率低下,因爲您將在每次調用時創建一組全新的閉包。即使像模塊模式(或揭示模塊模式)的解決方案也會遇到這個問題。如果你沒有創建太多的這個對象,上面的例子可能適合你。

+0

使用讓我意味着我無法訪問我的原型正確的頭? –

+0

是的。你放棄了爲此創建原型的能力。另外,它不是'let'唯一的,我可以在那裏使用'var'來達到同樣的效果。只是'let'是ES6中推薦的初始化變量的方法。 –

+0

這些不附加到您的原型。它們是由構造函數初始化的對象的方法。 – MinusFour