Encapsulation is a very useful technique in Object-Oriented programming which allows you to separate an abstraction's implementation from its interface class, thus enabling future changes to the implementation without affecting the interface. In this free HTML JavaScript tutorial, James Padolsey guides you how to create encapsulation in OOP JavaScript, please go to the detailed post for full instructions and JavaScript example codes.
- Demo
- Enlarge
- Reload
- New window
Generate your business videos by AI with voice or just text
Your first FREE AI Video App! Automate Your First AI Video. Create Your Professional Video In 5 Minutes By AI No Equipment Or Video Editing Skill Requred. Effortless Video Production For Content Marketers.
Real encapsulation, the hard way
For real encapsulation, the following criteria need to be met:
- You must be able to define private properties within the constructor and methods.
- You must be able to access and manipulate the private properties within the constructor and methods.
- The private properties must not be directly accessible from outside (i.e. as properties on the instance).
To fulfill these criteria we're going to need to create a small abstraction that will enable us to define our constructor, its methods, and its properties in a plain object, which will then be processed to produce the required constructor and prototype.
In accordance with convention, this abstraction will be named Class
. This is how it will typically work:
var Person = new Class({ _name: 'Blank', _age: 0, init: function(name, age) { this.name = name; this.age = age; }, toString: function() { return 'Name: ' + this.name + ', Age: ' + this.age; }, setAge: function(age) { this.age = age; }, setName: function(name) { this.name = name; } });
The underscore prefix tells Class
that we want those properties to be private. Privacy is achieved by retaining a truly private (in a closure) privates
array, each item within the array represents the private properties of
each instance. This will be clearer once you've seen the source (below).
Class
looks for an init
method to use as the constructor.
Here's the source for Class
, excluding the function:
function Class(o){ var id = 0, privates = {}, instancePrivates = [], constructor = function(){ this.__id = id++; // Copy privates over to new privates obj, // just for this instance. instancePrivates[this.__id] = { privates: merge({}, privates), constructor: this }; if (this.init) { this.init.apply(this, arguments); } return this; }, m; function method(name, fn) { constructor.prototype[name] = function() { var i, ret, thisPrivates = instancePrivates[this.__id] || {}; // Check constructor if (thisPrivates.constructor !== this) { // this.__id has been changed, exit. return; } thisPrivates = thisPrivates.privates; for (i in thisPrivates) { this[i] = thisPrivates[i]; } ret = fn.apply(this, arguments); for (i in thisPrivates) { thisPrivates[i] = this[i]; delete this[i]; } return ret; }; }; for (m in o) { // Test for privates if ( /^_/.test(m) ) { privates[m.replace(/^_/, '')] = o[m]; } else { method(m, o[m]); } } return constructor; }
There are cleaner ways of implementing this, but just for readability's sake, we're identifying each instance with a simple __id
property. Yes, this can be manipulated from the outside, but doing so would result in the methods not running.
It has some constraints, but it does provide us with encapsulation:
var Person = new Class({ _name: 'Blank', _age: 0, init: function(name, age) { this.name = name; this.age = age; }, toString: function() { return 'Name: ' + this.name + ', Age: ' + this.age; }, setAge: function(age) { this.age = age; }, setName: function(name) { this.name = name; } }); // Testing: var jimmy = new Person('Jim', 88); jimmy._name; // undefined jimmy.name; // undefined jimmy.toString(); // => "Name: Jim, Age: 88" jimmy.setName('Jimmy'); jimmy.toString(); // => "Name: Jimmy, Age: 88" jimmy.setAge(54); jimmy.toString(); // => "Name: Jimmy, Age: 54" jimmy._age; // undefined jimmy.age; // undefined
You can also have private methods, e.g.
var Box = new Class({ _width: 0, _height: 0, init: function(width, height) { this.width = width; this.height = height; }, info: function() { return 'Width: ' + this.width + ',\nHeight: ' + this.height + ',\nArea: ' + this.calcArea(); }, _calcArea: function() { return this.width * this.height; } }); var myBox = new Box(100, 100); myBox.calcArea; // undefined myBox._calcArea; // undefined myBox.info(); // => "Width: 100,\nHeight: 100,\nArea: 10000"
Conclusion
The method I used to achieve full encapsulation, while quite novel, isn't going to be appropriate in all situations. The population and clearing of private variables has to happen on every method call, and so will likely cause a significant overhead in some applications.
That said, I don't think the overhead will be all that significant, unless you've got a crazy amount of private properties/methods.
I hope this post has given you some insight into how you can achieve encapsulation and information-hiding in JavaScript.
- Sent (0)
- New
Generate your business videos by AI with voice or just text
chatGPTaz.com
Talk to ChatGPT by your mother language
AppAIVideo
Your first FREE AI Video App
Deepfake Video
Deepfake AI Video Maker
Deepfake
Deepfake AI Video Maker
AI Deep Fake
Deepfake AI Video Maker
AI Voice Generator
Most Realistic Text to Speech AI Solutions
AI Voice Generator
Most Realistic Text to Speech AI Solutions
AIvidio
AI Video Mobile Solutions
AIvideos
AI Video Platform & Solutions
AIvedio
AI Video App Maker
Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)
Artificial General Intelligence
Ai and higher level Artificial General Intelligence (AGI)
Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE
Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE
Faceswap AI Online
Swap Faces Video, Photo & GIFs Instantly with Powerful AI Tools - Faceswap AI Online FREE
Powerful AI Presentation PPT Maker for FREE
Build an impressive presentation with our free online AI presentation app
Your next top AI Assistant
Claude AI, developed by Anthropic
Your next top AI Assistant
Claude AI, developed by Anthropic
Temu Free $500 for New Users
Claim Free Temu $500 Credit via Affiliate & Influencer Program
Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing
Free TikTok Ads Credit
Master TikTok Ads for Your Business Marketing
Dall-E-OpenAI.com
Generate creative images automatically with AI
chatGPT4.win
Talk to ChatGPT by your mother language
First AI Product from Elon Musk - Grok/UN.com
Speak to Grok AI Chatbot with Your Language
Tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools
GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project
iPhoneKer.com
Save up to 630$ when buy new iPhone 16
Buy Tesla Optimus Robot
Order Your Tesla Bot: Optimus Gen 2 Robot Today for less than $20k