How to embed private members in JavaScript objects (1)

Source: Internet
Author: User

How to embed private members in JavaScript objects (1)

Recently, I developed a project named Angular Cloud Data Connector to help Angular developers use Cloud Data, especially Azure mobile services, using WEB standards, such as indexed DB ). I try to build a method that allows JavaScript developers to embed private members into an object.

The technology I used to solve this problem uses the closure space I named closure space ). In this getting started article, I want to share how to use it in your project and its impact on the performance and memory of mainstream browsers.

Before learning deeply, let's talk about why you need to use private members.) There is also an alternative method to simulate private members.

If you want to comment on this article, please push me (twitter): @ deltakosh.

1. why Private member Private Members)

When you create an object using JavaScript, you can declare the value member value members ). If you want to control the read/write access to them, you can declare it as follows:

 
 
  1. var entity = {}; 
  2.  
  3. entity._property = "hello world"; 
  4. Object.defineProperty(entity, "property", { 
  5.     get: function () { return this._property; }, 
  6.     set: function (value) { 
  7.         this._property = value; 
  8.     }, 
  9.     enumerable: true, 
  10.     configurable: true 
  11. }); 

In this way, you have full control over read and write operations. The problem is that the _ property member can still be directly accessed and modified.

This is why we need a more stable and reliable way to declare a private member, which is intelligently accessed through the object method.


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.