Home > Article > Web Front-end > Detailed code explanation of symbol + weakmap implementation of JavaScript private members
The biggest problem in WeakMap is that it cannot shim weak references. The secondary problem is that it is not convenient for debugging.
The WeakMap produced by shim is mainly because it cannot trace the life cycle of the instance, and the life cycle of the private members on the instance depends on the instance. Therefore, wouldn't it be good to put the instance-level private members on the instance? When the instance is gone, its attributes are naturally destroyed. The private storage area can be hidden using Symol.
This solution provides a createPrivate function, which will return a private token function, which is invisible to the outside world and obtained internally through the closure function. Passing in the current instance will return the private storage area of the current instance. The usage is as follows:
(function() { var $private = createPrivate(); // 私有成员 token 函数,可以传入对象参数,会作为原型链上的私有成员 function MyClass() { $private(this).privateProp = ‘privateProp' ; // 闭包内引用到privateStore, 用当前实例做 key,设置私有成员 } MyClass.prototype.getPrivateProp = function () { return $private(this).privateProp; }; })(); var my = new MyClass(); alert(my.getPrivateProp()); // ‘privateProp'; alert(my.privateProp); // 弹出 undefined,实例上并没有 privateProp 属性
The main purpose of the code is to implement the createPrivate function. The approximate implementation is as follows:
// createPrivate.js function createPrivate(prototype) { var privateStore = Symbol('privateStore'); var classToken = Symbol(‘classToken'); return function getPrivate(instance) { if (!instance.hasOwnProperty(privateStore)) { instance[privateStore] = {}; } var store = instance[classToken]; store[token] = store[token] || Object.create(prototype || {}); return store[token]; }; }
The above implementation has two layers of storage. The privateStore layer is a unified private member storage on the instance. area, and classToken corresponds to the private member definitions of different classes between inheritance levels. The base class has a private member area of the base class, and the private member areas of the subclass and the base class are different.
Of course, only one layer of storage can also be implemented. The two-layer storage is just for debugging convenience. You can directly use the Symbol ('privateStore') attribute to view the private parts of each level of the instance on the console.
The above is the detailed content of Detailed code explanation of symbol + weakmap implementation of JavaScript private members. For more information, please follow other related articles on the PHP Chinese website!