繁体   English   中英

设为不使用实例ID Javascript的私有成员

[英]Make a private member without using Instance Ids Javascript

我有一个LinkedList类,并且想将实例的head成员设为私有。 我看到了如何为每个实例创建密钥ID,而这些ID隐藏了LinkedList类的用户成员。 寻找其他方法来this.head设为私有

 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> 

我能想到的唯一方法是像这样的可憎:

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() { ... };
}

但是,这非常低效,因为您将在每次调用时创建一组全新的闭包。

甚至模块模式(或显示模块模式)之类的解决方案也遭受此问题的困扰。 如果您没有创建太多这个对象,那么上面的示例可能适合您。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM