search
HomeWeb Front-endJS TutorialHow to implement the grammatical features of private members and the implementation of private members based on JavaScript_javascript skills

Foreword

In the object-oriented programming paradigm, encapsulation is an essential concept, and in traditional object-oriented languages ​​such as Java and C, private members are an important way to achieve encapsulation. However, in JavaScript, there is indeed no support for private members in terms of grammatical features, which also makes developers use various tricks to implement private members in JS. The following will introduce the current implementation of private member features in JS. Several options and a comparison of their pros and cons.

Some existing implementation solutions

Common naming scheme

It is agreed that member names starting with an underscore '_' are regarded as private members. Only class member methods are allowed to be accessed and called, and private members are not allowed to be accessed externally. The simple code is as follows:

JavaScript

var MyClass = function () {
  this._privateProp = ‘privateProp';
};
MyClass.prototype.getPrivateProp = function () {
  return this._privateProp;
};
var my = new MyClass();
alert(my.getPrivateProp()); // ‘privateProp';
alert(my._privateProp); // 并未真正隐藏,依然弹出 ‘privateProp'

Advantages

There is no doubt that naming convention is the simplest solution to implement private members without any code-level work.
Debugging is convenient, and you can directly see the private members on the object on the console, making it easy to troubleshoot problems.
Good compatibility, supported by ie6

Not enough

There is no way to prevent external access and changes to private members. If a developer who does not know or does not comply with the agreement changes private attributes, there is nothing that can be done.
Everyone must be forced or persuaded to abide by this agreement. Of course, this is not a big problem in a team with code standards.

es6 symbol solution

In es6, a Symbol feature was introduced, which was introduced to implement private members.
The main idea is to generate a random and unique string key for the name of each private member. This key is invisible to the outside world. Internal visibility is achieved through the closure variable of js. The sample code is as follows:

JavaScript

(function() {
   var privateProp = Symbol(); // 每次调用会产生一个唯一的key
   function MyClass() {
     this[privateProp] = ‘privateProp'; // 闭包内引用到这个 key
   }
   MyClass.prototype.getPrivateProp = function () {
     return this[privateProp];
   };
})();
var my = new MyClass();
alert(my.getPrivateProp()); // ‘privateProp';
alert(my.privateProp); // 弹出 undefined,因为成员的key其实是随机字符串

Advantages

It makes up for the shortcomings of the naming convention scheme, and external parties cannot obtain access to private members through normal channels.
The convenience of debugging is acceptable. Generally, a string parameter is passed to the constructor of symbol, and the corresponding private property name on the console will be displayed as: Symbol(key)

The compatibility is good, and browsers that do not support Symbol can be easily shimmed out.

Not enough

The writing is a little awkward. A closure variable must be created for each private member so that the internal method can access it.
Externally, you can still obtain the symbol property name of the instance through Object.getOwnPropertySymbols, and obtain access rights to private members through this name. This scenario occurs relatively rarely, and the level of developers who know this approach is believed to be capable enough to know the impact of their actions, so this shortcoming is not a real shortcoming.

es6 WeakMap solution

Map and WeakMap containers were introduced in es6. The biggest feature is that the key name of the container can be any data type. Although the original intention is not to implement the introduction of private members, it can unexpectedly be used to implement private member features.

The main idea is to create a WeakMap container at the class level to store the private members of each instance. This container is invisible to the outside world and visible to the inside through closures; internal methods obtain the instance as a key name. Private members of the corresponding instance on the container. The sample code is as follows:

JavaScript

(function() {
   var privateStore = new WeakMap(); // 私有成员存储容器
   function MyClass() {
     privateStore.set(this, {privateProp: ‘privateProp'}); // 闭包内引用到privateStore, 用当前实例做 key,设置私有成员
   }
   MyClass.prototype.getPrivateProp = function () {
     return privateStore.get(this).privateProp; 
   };
})();
var my = new MyClass();
alert(my.getPrivateProp()); // ‘privateProp';
alert(my.privateProp); // 弹出 undefined,实例上并没有 privateProp 属性

优点

弥补了命名约定方案的缺陷,外部无法通过正常途径获得私有成员的访问权。
对 WeakMap 做一些封装,抽出一个私有特性的实现模块,可以在写法上相对 Symbol 方案更加简洁干净,其中一种封装的实现可以查看参考文章3。
最后一个是个人认为最大的优势:基于 WeakMap 方案,可以方便的实现保护成员特性(这个话题会在其他文章说到:))

不足

不好调试,因为是私有成员都在闭包容器内,无法在控制台打印实例查看对应的私有成员
待确认的性能问题,根据 es6的相关邮件列表,weakmap 内部似乎是通过顺序一一对比的方式去定位 key 的,时间复杂度为 O(n),和 hash 算法的 O(1)相比会慢不少

最大的缺陷则是兼容性带来的内存膨胀问题,在不支持 WeakMap 的浏览器中是无法实现 WeakMap 的弱引用特性,因此实例无法被垃圾回收。 比如示例代码中 privateProp 是一个很大的数据项,无弱引用的情况下,实例无法回收,从而造成内存泄露。

现有实现方案小结

从上面的对比来看,Symbol方案最大优势在于很容易模拟实现;而WeakMap的优势则是能够实现保护成员, 现阶段无法忍受的不足是无法模拟实现弱引用特性而导致的内存问题。于是我的思路又转向了将两者优势结合起来的方向。

Symbol + 类WeakMap 的整合方案

在 WeakMap 的方案中最大的问题是无法 shim 弱引用,较次要的问题是不大方便调试。

shim 出来的 WeakMap 主要是无法追溯实例的生命周期,而实例上的私有成员的生命周期又是依赖实例, 因此将实例级别的私有成员部分放在实例上不就好了? 实例没了,自然其属性也随之摧毁。而私有存储区域的隐藏则可以使用 Symol 来做。

该方案的提供一个 createPrivate 函数,该函数会返回一个私有的 token 函数,对外不可见,对内通过闭包函数获得, 传入当前实例会返回当前实例的私有存储区域。使用方式如下:

JavaScript

(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 属性

代码中主要就是实现 createPrivate 函数,大概的实现如下:

JavaScript

// 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];
   };
}

上述实现做了两层存储,privateStore 这层是实例上统一的私有成员存储区域,而 classToken 对应的则是继承层次之间不同类的私有成员定义,基类有基类的私有成员区域,子类和基类的私有成员区域是不同的。

当然,只做一层的存储也可以实现,两层存储仅仅是为了调试方便,可以直接在控制台通过Symbol(‘privateStore')这个属性来查看实例各个层次的私有部分。

奇葩的 es5 property getter 拦截方案

该方案纯粹是闲得无聊玩了玩,主要是利用了 es5 提供的 getter,根据 argument.callee.caller 去判断调用场景,如果是外部的则抛异常或返回 undefined, 如果是内部调用则返回真正的私有成员,实现起来比较复杂,且不支持 strict 模式,不推荐使用。 有兴趣的同学可以看看实现。

总结

以上几个方案对比下来,我个人是倾向 Symbol+WeakMap 的整合方案,结合了两者的优点,又弥补了 WeakMap 的不足和 Symbol 书写的冗余。 当然了,我相信随着 JS 的发展,私有成员和保护成员也迟早会在语法层面上进行支持,正如 es6 对 class 关键字和 super 语法糖的支持一样, 只是现阶段需要开发者使用一些技巧去填补语言特性上的空白。

Javascript私有成员的实现方式

总体来讲这本书还是可以的,但看完这本书还留了几个问题一直困扰着我,如js中私有变量的实现,prototype等,经过自己一系列测试,现在终于弄明白了。

很多书上都是说,Javascript是不能真正实现Javascript私有成员的,因此在开发的时候,统一约定 __ 两个下划线开头为私有变量。

后来,发现Javascript中闭包的特性,从而彻底解决了Javascript私有成员的问题。

 function testFn(){ 
    var _Name;//定义Javascript私有成员 
    this.setName = function(name){ 
     _Name = name; //从当前执行环境中获取_Name 
    } 
    this.getName = function(){ 
     return _Name; 
    } 
}// End testFn 
var test = testFn(); 
alert(typeof test._Name === "undefined")//true 
test.setName("KenChen"); 

test._Name 根本访问不到,但是用对象方法能访问到,因为闭包能从当前的执行环境中获取信息。

接下来我们看看,共有成员是怎样实现的

function testFn(name){ 
  this.Name = name; 
  this.getName = function(){ 
   return this.Name; 
  } 
} 
var test = new testFn("KenChen"); 
test.getName(); //KenChen 
test.Name = "CC"; 
est.getName();//CC 

接下来在看看类静态变量是怎样实现的

function testFn(){ 
} 
testFn.Name = "KenChen"; 
alert(testFn.Name);//KenChen 
testFn.Name = "CC"; 
alert(testFn.Name);//CC 

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 jQuery Fun and Games Plugins10 jQuery Fun and Games PluginsMar 08, 2025 am 12:42 AM

10 fun jQuery game plugins to make your website more attractive and enhance user stickiness! While Flash is still the best software for developing casual web games, jQuery can also create surprising effects, and while not comparable to pure action Flash games, in some cases you can also have unexpected fun in your browser. jQuery tic toe game The "Hello world" of game programming now has a jQuery version. Source code jQuery Crazy Word Composition Game This is a fill-in-the-blank game, and it can produce some weird results due to not knowing the context of the word. Source code jQuery mine sweeping game

How do I create and publish my own JavaScript libraries?How do I create and publish my own JavaScript libraries?Mar 18, 2025 pm 03:12 PM

Article discusses creating, publishing, and maintaining JavaScript libraries, focusing on planning, development, testing, documentation, and promotion strategies.

jQuery Parallax Tutorial - Animated Header BackgroundjQuery Parallax Tutorial - Animated Header BackgroundMar 08, 2025 am 12:39 AM

This tutorial demonstrates how to create a captivating parallax background effect using jQuery. We'll build a header banner with layered images that create a stunning visual depth. The updated plugin works with jQuery 1.6.4 and later. Download the

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.