OOP-Encapsulation-Theory-GOOD-Explanations-Private-Methods

Patient Tools

Read, save, and share this guide

Use these quick tools to make this medical article easier to read, print, save, or share with a family member.

Article Summary

An object can store data in one of two ways: as a property or as a variable. The method that you choose will have substantial ramifications on data visibility. Object properties are created using the "this." prefix. The name that follows the dot will identify a new property to add to the object's properties collection. That makes it a poor choice for storing private data....

Educational health guideWritten for patient understanding and clinical awareness.
Reviewed content workflowUse writer and reviewer profiles for stronger trust.
Emergency safety firstUrgent warning signs are highlighted below.

Seek urgent medical care if you notice

These warning signs are general safety guidance. Local emergency numbers and clinical judgment should always come first.

  • Severe symptoms, breathing difficulty, fainting, confusion, or rapidly worsening illness.
  • New weakness, severe pain, high fever, or symptoms after a serious injury.
  • Any symptom that feels urgent, unusual, or unsafe for the patient.
1

Emergency now

Use emergency care for severe, sudden, rapidly worsening, or life-threatening symptoms.

2

See a doctor

Book a professional medical evaluation if symptoms persist, worsen, recur often, affect daily activities, or occur in a high-risk patient.

3

Learn safely

Use this article to understand possible causes, tests, treatment options, prevention, and questions to ask your clinician.

An object can store data in one of two ways: as a property or as a variable. The method that you choose will have substantial ramifications on data visibility. Object properties are created using the “this.” prefix. The name that follows the dot will identify a new property to add to the object’s properties collection. That makes it a poor choice for storing private data. Variables, on the other hand, are created using the “var” keyword. It is subject to the rules of variable scoping and are more private for that reason. The following Person object contains a number of properties, accessible via setter and getter functions:

function Person() {
	//properties/fields
	this.name = "Rob Gravelle";
	this.height = 68;
	this.weight = 170;
	this.socialInsuranceNumber = "555 555 555";

	//methods/actions
	this.setHeight = function(height) {
		this.height = height;
	};
	this.getHeight = function() {
		return this.height;
	};
	this.setWeight = function(weight) {
		this.weight = weight;
	};
	this.getWeight = function() {
		return this.weight;
	};
	this.setName = function(name) {
		this.name = name;
	};
	this.getName = function() {
		return this.name;
	};
	this.setSocialInsuranceNumber = function(socialInsuranceNumber) {
		this.socialInsuranceNumber = socialInsuranceNumber;
	};

	return this;
}
//instanciate the Person class
var aPerson = new Person();
var myName = aPerson.getName(); //myName now contains "Rob Gravelle"
aPerson.setName("mud"); //change the name
var myName = aPerson.getName(); //aPerson's name is now "mud"
var sinNo = aPerson.getSocialInsuranceNumber(); //will also throw an exception.  No getter implemented for that field!

We define these function by prepending the this keyword which makes them accessible from the outside (see Encapsulation). Notice that the functions have full access to the properties.

to try calling the fields directly:

//instanciate the Person class
var aPerson = new Person();
var myName = aPerson.name; //this works
//as does this:
aPerson.name = "whatever.";

The lesson here is that object member variables are public, while those that are stored as variables are private. Our second example uses variables instead of properties to hide all the data fields:

function Person() {
	//properties/fields
	var name = "Rob Gravelle";
	var height = 68;
	var weight = 170;
	var socialInsuranceNumber = "555 555 555";

	//methods/actions
	this.setHeight = function(newHeight) {
		height = newHeight;
	};
	this.getHeight = function() {
		return height;
	};
	this.setWeight = function(newWeight) {
		weight = newWeight;
	};
	this.getWeight = function() {
		return weight;
	};
	this.setName = function(newName) {
		name = newName;
	};
	this.getName = function() {
		return name;
	};
	this.setSocialInsuranceNumber = function(newSocialInsuranceNumber) {
		socialInsuranceNumber = newSocialInsuranceNumber;
	};

	return this;
}
//instanciate the Person class
var aPerson = new Person();
var myName = aPerson.name; //this no longer works
var myName = aPerson.getName(); //this does

Notice that the setters’ argument is named differently than the underlying variable. That’s to avoid duplicate variables within the same scope.

Encapsulation

Encapsulation is the ability of an object to be a container (or capsule) for its member properties, including variables and methods. As a fundamental principle of object oriented programming (OOP), encapsulation plays a major role in languages such as C++ and Java. However, in scripting languages, where types and structure are not actively enforced by the compiler or interpreter, it is all-too-easy to fall into bad habits and write code that is brittle, difficult to maintain, and error-prone.

We create objects with methods, properties, and attributes.

When we make them bundled inside an object it’s known as encapsulation. When these methods and attributes are abstracted from other objects, this is known as abstraction.

JavaScript is designed on a simple object-based paradigm. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property’s value can be a function, in which case the property is known as a method. In addition to objects that are predefined in the browser, you can define your own objects.

Two principles with OOP in JS are:

Object Creation Pattern (Encapsulation)

Object Reuse Pattern (Inheritance)

Private member variables in objects.

All properties or let us say member variables defined with the “this” keyword inside a function object is of public type, which mean that they can be accessed from outside of a created object.

function Person(n) {
  // name and getName ar both public
  this.name = n
  this.getName = function() {
    return this.name
  }
}

All variables, which are defined with the “var” keyword (and NOT ‘this’) and all the methods that a constructor function is private and therefore NOT accessible from outside of a created object. The same applies to all function arguments.

– One of the most important things in object-oriented programming (OOP) is data encapsulation, which means to make private properties and then define public access methods to change these.

  • All public methods, which are defined inside a function object, have access to all defined private member variables and private methods in a created object.

  • Public methods defined on the outside of a function object can not access private member variables as they are not defined in the same scope as those.

function Rectangle(h, w) {
  var width = w // Both the 'width' and 'w' is private
  var height = h // Both the 'height' and 'h' is private
  this.setWidth = function(w) {
    width = w
  }
  this.setHeight = function(h) {
    height = h
  }
  this.getWidth = function() {
    return width
  }
  this.getHeight = function() {
    return height
  }
  this.constructor.prototype.getDiagonal = function() {
    return Math.sqrt(height * height + width * width)
  }
}

Rectangle.prototype.getArea = function() {
  // We must use accessors in a prototype kind of method,
  // then these methods can not access the private members
  // of a created object.
  return this.getWidth() * this.getHeight()
}

var rect = new Rectangle(60, 70)
rect.setHeight(20)
console.log(rect.getArea()) // => 1400

Private methods (in the below example the born() method) have no direct access to properties that are defined to be public with “this” keyword in a function object.

To achieve this, one can define a variable that has the same reference as “this” refers to. And thats exactly whey I have to create the var thisObj in the below Person()

function Person(n, y) {
  var name = n
  var year = y
  // Set a variable to the same as this
  var thisObj = this
  this.setName = function(n) {
    name = n
  }
  this.getName = function() {
    return name
  }
  this.setYear = function(y) {
    year = y
  }
  this.getYear = function() {
    return year
  }
  var born = function() {
    var nYear = new Date().getFullYear()
    // Use the thisObj variable which is the same as this refer to.
    return nYear - thisObj.getYear()
    // If I just used 'this' directly here, will get error -
    // this.getYear is not a function
    // The "this" keyword inside this function refers to an object
    // created by the constructor function of this function object.
  }
  this.getBornYear = function() {
    return born()
  }
}
var person = new Person("Nikita", 60)

console.log(person.getName()) // => Nikita
console.log(person.getBornYear()) // => 1959
console.log(person.born()) // => person.born is not a function

This is an example of “class-free” object oriented programming

const MyObj3 = initVal => {
	let myVal = initVal;
	return {
		get: function() {
			return myVal;
		},
		set: function(val) {
			myVal = val;
		}
	};
};

Just like the approach above, we can use it to create an object like this:

const x = MyObj3(0)

The myVal variable is essentially private, which means we can no longer access it using x.myVal like in the other implementations above. Instead we have to call the getter function:

x.get()

Closures enable a strong contract

The variable is conceptually “saved” inside the object returned from the function thanks to Javascript closures. This means that we can set the value with the setter method (i.e. x.set(2)), but attempting to directly change the field (i.e. x.myVal = 2) won’t do anything.

The greatest part of having these explicit setters and getters is that the object now has a strong contract/interface with the outside world. The state is fully encapsulated and the only ways in and out of the object is through the setters and getters.

One drawback about using closures is the issue of performance. While there doesn’t seem to be any difference when creating an object, method calls on the object using closures were about 80% slower.

 
Patient safety assistant

Check your symptom safely

Hi, I am RX Symptom Navigator. I can help you understand what to read next and what warning signs need care.
Warning: Do not use this in emergencies, pregnancy, severe illness, or as a substitute for a doctor. For children or teens, use with a parent/guardian and clinician.
A rural-friendly guide: warning signs, when to see a doctor, related articles, tests to discuss, and OTC safety education.
1 Symptom 2 Severity 3 Safe guidance
First safety question

Is there chest pain, breathing trouble, fainting, confusion, severe bleeding, stroke-like weakness, severe injury, or pregnancy danger sign?

Choose quickly

Browse by body area
Start here: Write or select a symptom. The guide will show warning signs, doctor guidance, diagnostic tests to discuss, OTC safety education, and related RX articles.

Important: This tool is educational only. It cannot diagnose, treat, or replace a doctor. OTC information is not a prescription. In an emergency, contact local emergency services or go to the nearest hospital.

Doctor visit helper

Prepare before seeing a doctor

A simple rural-patient checklist to help you explain symptoms clearly, ask better questions, and avoid unsafe self-treatment.

Safety note: This is not a prescription or diagnosis. For severe symptoms, pregnancy danger signs, children with serious illness, chest pain, breathing difficulty, stroke-like weakness, or major injury, seek urgent care.

Which doctor may help?

Start with a registered doctor or the nearest qualified health center.

What to tell the doctor

  • Write when the problem started and how it changed.
  • Bring old prescriptions, investigation reports, and current medicines.
  • Write allergies, pregnancy status, diabetes, kidney/liver disease, and major past illnesses.
  • Bring one family member if the patient is weak, elderly, confused, or a child.

Questions to ask

  • What is the most likely cause of my symptoms?
  • Which danger signs mean I should go to hospital quickly?
  • Which tests are necessary now, and which can wait?
  • How should I take medicines safely and what side effects should I watch for?
  • When should I come for follow-up?

Tests to discuss

  • Vital signs: temperature, pulse, blood pressure, oxygen saturation
  • Basic physical examination by a clinician
  • CBC, urine test, blood sugar, or imaging only when clinically needed

Avoid these mistakes

  • Do not use antibiotics, steroid tablets/injections, or strong painkillers without proper medical advice.
  • Do not hide pregnancy, kidney disease, ulcer, allergy, or blood thinner use.
  • Do not delay emergency care when danger signs are present.

Medicine safety and first-aid guide

This section is for patient education only. It does not replace a doctor, pharmacist, or emergency care.

Safe first steps

  • Rest, drink safe water, and observe symptoms carefully.
  • Keep a written note of symptoms, duration, temperature, medicines already taken, and allergy history.
  • Seek medical care quickly if symptoms are severe, worsening, or unusual for the patient.

OTC medicine safety

  • For mild pain or fever, ask a registered pharmacist or doctor before using common over-the-counter pain/fever medicines.
  • Do not combine multiple pain medicines without advice, especially if you have kidney disease, liver disease, stomach ulcer, asthma, pregnancy, or take blood thinners.
  • Do not give adult medicines to children unless a qualified clinician advises it.

Avoid these mistakes

  • Do not start antibiotics without a proper medical decision.
  • Do not use steroid tablets or injections casually for quick relief.
  • Do not delay emergency care because of home remedies.

Get urgent help if

  • Severe symptoms, confusion, fainting, breathing difficulty, chest pain, severe dehydration, or sudden weakness need urgent medical care.
Medicine names, dose, and timing must be decided by a qualified clinician or pharmacist after checking age, pregnancy, allergy, other diseases, and current medicines.

For rural patients and family caregivers

Patient health record and symptom diary

Write your symptoms, medicines already taken, test results, and questions before visiting a doctor. This note stays on your device unless you print or copy it.

Doctor to discuss: Doctor / qualified healthcare provider
Tests to discuss with doctor
  • Basic vital signs: temperature, pulse, blood pressure, oxygen level if needed
  • Relevant blood, urine, imaging, or specialist tests only after clinical assessment
Questions to ask
  • What is the most likely cause of my symptoms?
  • Which warning signs mean I should go to emergency care?
  • Which tests are really needed now?
  • Which medicines are safe for my age, pregnancy status, allergy, kidney/liver/stomach condition, and current medicines?

Emergency warning signs such as chest pain, severe breathing difficulty, sudden weakness, confusion, severe dehydration, major injury, or loss of bladder/bowel control need urgent medical care. Do not wait for online information.

Safe pathway to proper treatment

Patient care roadmap

Use this simple roadmap to understand the next safe steps. It is educational and does not replace examination by a doctor.

Go to emergency care if you notice:
  • Severe or rapidly worsening symptoms
  • Breathing difficulty, chest pain, fainting, confusion, severe weakness, major injury, or severe dehydration
Doctor / service to discuss: Qualified healthcare provider; specialist depends on symptoms and examination.
  1. Step 1

    Check danger signs first

    If danger signs are present, seek emergency care and do not wait for online information.

  2. Step 2

    Record the symptom story

    Write when symptoms started, severity, medicines already taken, allergies, pregnancy status, and test results.

  3. Step 3

    Visit a qualified clinician

    A doctor, nurse, or qualified healthcare provider can examine you and decide which tests or treatment are needed.

  4. Step 4

    Do only useful tests

    Do tests after clinical assessment. Avoid unnecessary tests, random antibiotics, or repeated medicines without diagnosis.

  5. Step 5

    Follow up and return early if worse

    If symptoms worsen, new warning signs appear, or treatment is not helping, return for review quickly.

Rural patient practical tips
  • Take a written symptom diary and all previous prescriptions/test reports.
  • Do not hide medicines already taken, even herbal or over-the-counter medicines.
  • Ask which warning signs mean urgent referral to hospital.

This roadmap is for education. A real diagnosis and treatment plan requires history, examination, and clinical judgment.

RX Patient Help

Ask a health question safely

Write your symptom story. A health professional or site editor can review it before any answer is prepared. This box is not for emergency care.

Emergency first: Severe chest pain, breathing trouble, unconsciousness, stroke signs, severe injury, heavy bleeding, or rapidly worsening symptoms need urgent local medical care now.

Frequently Asked Questions

Is this article a replacement for a doctor?

No. It is educational content only. Patients should consult a qualified clinician for diagnosis and treatment.

When should I seek urgent care?

Seek urgent care for severe symptoms, rapidly worsening condition, breathing difficulty, severe pain, neurological changes, or any emergency warning sign.

References

Add references, clinical guidelines, textbooks, journal articles, or trusted medical sources here. You can edit this area from the RX Article Professional Blocks panel.