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>
使用让我意味着我无法访问我的原型正确的头? –
是的。你放弃了为此创建原型的能力。另外,它不是'let'唯一的,我可以在那里使用'var'来达到同样的效果。只是'let'是ES6中推荐的初始化变量的方法。 –
这些不附加到您的原型。它们是由构造函数初始化的对象的方法。 – MinusFour