As per Wikipedia page, Encapsulation is the packing of data and functions into a single component….It allows selective hiding of properties and methods in an object… In OOPs based language, access specifier such as “public”, “private” and “protected” are used to specify the access properties of member variables and methods. Following rule applies for a Class member variable and methods:
function Person() {
this.name = "Calvin";
age = 25;
}
In order to access the value of private variable, it needs to be accessed using a public method. Take a look at example below where getAge is used to access the value of “age” which is a private variable.
function Person() {
this.name = "Calvin";
age = 25;
this.getAge = function() {
return age;
}
}
Following rule applies for an object:
var calvin = {
name: "Calvin Hobbes",
age: 15,
getAge: function() {
return this.age;
}
}
Pay attention to the fact that “this” or “var” keyword is not needed (not supported as well; throws error) to be used with member variable and methods. However, “this” keyword is used to access the member variable within a method. If not used, it will look for local variable, “age” defined using getAge method.
// Following represents class, Company, that takes two arguments such as name and age.
// Pay attention to "this" keyword which makes the variable and method, public
function Company(name, age) {
// Name & Age variables are public; Meaning, they can be accessed by the instance of the class
this.name = name;
this.age = age;
// type is a private variable; It can not be accessed publicly
var type = 1;
this.getName = function() {
return this.name;
}
this.getAge = function() {
return this.age;
}
this.getType = function() {
return type;
}
}
var infosys = new Company( "Infosys Technologies");
// Below would print Infosys Technologies
console.log( infosys.name );
// Below would print "undefined". Note the "var" keyword. Even if you do not use "var" and define the variable as it is, it is private in nature.
// In order to access the private variable value, it needs to be accessed using a public method.
console.log( infosys.getType() );
When building a Retrieval-Augmented Generation (RAG) application powered by Large Language Models (LLMs), which combine…
Last updated: 25th Jan, 2025 Have you ever wondered how to seamlessly integrate the vast…
Artificial Intelligence (AI) agents have started becoming an integral part of our lives. Imagine asking…
In the ever-evolving landscape of agentic AI workflows and applications, understanding and leveraging design patterns…
In this blog, I aim to provide a comprehensive list of valuable resources for learning…
Have you ever wondered how systems determine whether to grant or deny access, and how…