JavaScript private attributes implementation tutorial

Source: Internet
Author: User
Tags closure coding standards data structures hash

JavaScript is not considered by many people as an object-oriented language for many reasons. For example, JavaScript does not have classes and cannot provide traditional class inheritance. For example, JavaScript cannot implement information hiding, private members cannot be implemented. This article does not aim to break the above misunderstanding (in fact, I am also confused), but simply introduces several JavaScript methods to implement private attributes and their respective advantages and disadvantages.


1. Implementation methods based on coding conventions

Many coding standards define variables starting with dashes _ as private members to facilitate collaboration with team developers. The implementation method is as follows:

Function Person (name ){
This. _ name = name;
}

Var person = new Person ('job ');

This method is just a standard agreement and can be easily broken. In addition, the private attributes are not implemented. The instance person in the above code can directly access the _ name attribute:

Alert (person. _ name); // 'job'

2. Closure-based implementation

Another common method is to use the closure feature of JavaScript. The constructor defines local variables and special functions. Its instances can only access this variable through special functions, as shown below:

Function Person (name) {var _ name = name; this. getName = function () {return _ name;} var person = new Person ('job ');


The advantage of this method is that private attributes are hidden. The instance of Person cannot directly access the _ name attribute and can only be obtained through the special function getName:

Alert (person. _ name); // undefined
Alert (person. getName (); // 'job'

Many developers use closures and privileged functions to define and access private attributes. Douglas Crockford also mentioned this method in his blog. However, this method has some defects:

Private variables and privileged functions can only be created in Constructors. Generally, the constructor is only responsible for creating new objects, and the methods should be shared with prototype. In essence, privileged functions exist in each instance rather than prototype, which increases resource usage.

3. Implementation method based on strong reference hash

JavaScript does not support Map data structures. The so-called strong reference hash mode is actually a variant of the Map mode. Simply put, a unique identifier is added to each instance. The identifier is the key and the corresponding value is the private attribute of the instance. The key-value pair is stored in an Object. The implementation method is as follows:

Var Person = (function () {var privateData = {}, privateId = 0; function Person (name) {Object. defineProperty (this, "_ id", {value: privateId ++}); privateData [this. _ id] = {name: name};} Person. prototype. getName = function () {return privateData [this. _ id]. name ;}; return Person ;}());

The preceding code has the following features:

Use the self-executed function to create the Person class. The variables privateData and privateId are shared by all instances;
PrivateData is used to store the key-value of the private attribute name of each instance, and privateId is used to assign a unique identifier _ id for each instance;
The getName method exists on prototype and is shared by all instances.

This method is basically the best solution in the current ES5 environment. However, there is still a fatal defect: the scattered list privateData is strongly referenced by each instance, so that the instance cannot be reclaimed. If there are a large number of instances, it will inevitably lead to memory leak.

The essence of the above problems is the JavaScript closure reference, and only the key values of the string type that are the most scattered list can be used. To solve these two problems, the new WeakMap in ES6 can be well solved.

4. WeakMap-based implementation

WeakMap has the following features:

The object type can be used as the key value;
Weak references.

Based on the features of WeakMap, you do not need to create a unique identifier for each instance, because the instance itself can be used as the key of WeakMap. The improved code is as follows:

Var Person = (function () {var privateData = new WeakMap (); function Person (name) {privateData. set (this, {name: name});} Person. prototype. getName = function () {return privateData. get (this ). name ;}; return Person ;}());


The improved code is not only much clean, but WeakMap is a type of weak reference hash, which means that if there are no other references and the key references the same object, this object will be recycled as garbage. Solved the problem of memory leakage.

Unfortunately, the browser's support rate for WeakMap is not satisfactory, and it still needs to wait for it to be put into the production environment.


Javascript private property private method code example

Function People (name) {var _ name = name; // private attribute function privateMethod () {// private method alert ('private');} return {age: 0, // public property setName: function (name) {// public method _ name = name;}, getName: function () {// public method return _ name ;}}} var p = People ('hangsan'); // p. privateMethod (); console. log (p. getName (); console. log (p. age); p. age = 1; p. setName ('lisi'); console. log (p. getName (); console. log (p. age );


Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.