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:
- var entity = {};
-
- entity._property = "hello world";
- Object.defineProperty(entity, "property", {
- get: function () { return this._property; },
- set: function (value) {
- this._property = value;
- },
- enumerable: true,
- configurable: true
- });
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.