Encapsulation in Javascript

Someone asked me about how could I implement encapsulation in Javascript and I got stumped, I had no answer to it, and after studying how its done, it really is a bit tricky.

Encapsulation in Javascript

Now I tried to sit and think about how would I try to do this. How would I add a private member to an object (which is technically a assoc array) in Javascript?

I started by reading up on Variable Scope in javascript, because that’ll be the only way we’ll be able to restrict access to a variable. So,

Unlike most programming languages, JavaScript does not have block-level scope (variables scoped to surrounding curly brackets); instead, JavaScript has function-level scope. Variables declared within a function are local variables and are only accessible within that function or by functions inside that function.  Source

Consider this:

function mainfunction(var1, var2) {
 var mainvar = "Hello";
 
 function inner1() {
 return mainvar + " " + var1;
 }
 
 return inner1;
}

var main_func_output = mainfunction("Aneesh", "Dogra");

console.log(main_func_output());

Here, when we execute mainfunction it gets us the inner1’s function reference (can I say function pointer?). mainfunction after returning inner1’s function finishes. But still, the output shows “Hello Aneesh”. That means inner1 could still use mainvar, even though the mainfunction has already returned.

Interesting! What we just used here is called a closure.

A closure is an inner function that has access to the outer (enclosing) function’s variables—scope chain. The closure has three scope chains: it has access to its own scope (variables defined between its curly brackets), it has access to the outer function’s variables, and it has access to the global variables. Source

We can use the idea of closure to do encapsulation in javascript. Here’s how:

function MyClass() {
 // private variables go here
 var privar1 = "Hello";
 var privar2 = "Aneesh";
 
 
 return {
 greet: function () {
 return privar1 + " " + privar2;
 },
 update_greeting: function (new_greeting) {
 privar1 = new_greeting;
 }
 }
}

var object = MyClass();
console.log(object.greet());

object.update_greeting("Holla")
console.log(object.greet());

 

UBER, Taxi Drivers, Circus and Guitars on Airplanes

I am having an amazing night. I am on my way to Bangalore, travelling there majorly to take part in HackIndia.io. I am at the Indra Gandhi Airport now, and am loving the trip already.

The Pre-Trip

I went to this amazing gig by the Circus in Turquoise cottage. I love them and I am a great fan of F.O.P.S. now!

The Uber Ride

This is gonna be the most interesting part of the story, so listen up!

It took the driver around 15 mins to reach the GovindPuri Metro; after that I had to instruct him the way to my college. He was a pretty interesting guy, greeted me well and we started talking. I asked him about how he was in Uber and we started talking about it.

 

Me: How do you get an uber request?
Driver: I get a notification, if I am in the nearby area and am signed-in in the app.
Me: Do you have a different app?
Driver: Yes. I think its different, its for drivers. 
Me: How do you register as a driver?
Driver: There is an Uber office in Haus Khaz. Drivers give photocopies of their documents, including driving license, address proof, .
Me: How much do you get paid?
Driver: It depends on the time. In the day time its around 300 per ride + 80% of what your bill is.
Me: So uber gives you 300 per ride and gives you 80% of the fare, it makes 20% of your fare only?
Driver: He confirmed yes. 
Me: If uber is in loss now in an average cab request, how are they befitting?
* silence *
We both then started discussing what their revenue model.
Driver: I think they'll cut shot on the 300 per ride they are offering now, or maybe increase the price per km in future?
Me: I think they're doing that. Do you get 2x in peak hours?
Driver: Yes. We do get 2x.
Me: Okay then that's not it.

So uber is making loss on almost all the transactions you make. I can’t find what their revenue model is now.

Airport

I love this place. It has conveyors, it is very spacious, people are so calm most of the time. I even had a chat with the guy who frisked me, apparently he knew some one with the same last name as me and he found “dogras” very matured. I smiled in agreement and passed.

I then went for my check-in; humbly greeted by the staff. I am going to a place for a while in the winters, and wanted to know if I can carry my guitar on the flight. YES YOU CAN. I had done some research about it already and people on the forums are like, no it doesn’t fit the baggage restrictions. Even though it doesn’t, it is allowed as a cabin bag in Air Asia. (thanks so much AirAsia!).

Its 5:25AM – light blueish outside. Thank you so much Tata Docomo, for the internet here.

What I thought about pointers and what they really are?

One bright morning, the day I had started learning C, I stumbled onto something called pointers. A guy on the forums claimed that if you know pointers you know C. I planned to study pointers all night-continuing-to-morning. The tutorial mentioned about something called an address. The addresses related to memory and how they store data is something you need to know before you study pointers. Lets start with strings.

How are strings represented in memory?

See boy, strings say you gotta have the chars, a null byte and n + 1 bytes of memory.

If its on the stack, the string would be like this:

  • H
  • E
  • L
  • L
  • O
  • \0

The ordering of the characters depending on the endianess. What is char *?

Its a variable holding the address of the first character of the string. Literally!

We’ve arrived at the definition of a pointer here. That’s what a pointer is always, a variable holding the address. Its 4 bytes on a 32 bit system and 8 bytes on the 64 bit one. The pointer still have types thought, it always contains a memory address but the pointer behaves differently for different types. Read more about it when we discuss offsets.

How are arrays represented in memory?

It’s a similar deal with arrays, except a few facts:

char [] != char *

For 1 year since I started learning C, I assumed they were the same thing.

2.2: But I heard that char a[] was identical to char *a.

Not at all.  (What you heard has to do with formal parameters to functions; see question 2.4.)  Arrays are not pointers.  The array declaration “char a[6];” requests that space for six characters be set aside, to be known by the name “a.”  That is, there is a location named “a” at which six characters can sit. The pointer declaration “char *p;” on the other hand, requests a place which holds a pointer.  The pointer is to be known by the name “p,” and can point to any char (or contiguous array of chars) anywhere.

As usual, a picture is worth a thousand words.  The statements

	char a[] = "hello";
	char *p = "world";

would result in data structures which could be represented like this:

	   +---+---+---+---+---+---+
	a: | h | e | l | l | o |\0 |
	   +---+---+---+---+---+---+
	   +-----+     +---+---+---+---+---+---+
	p: |  *======> | w | o | r | l | d |\0 |
	   +-----+     +---+---+---+---+---+---+

It is important to realize that a reference like x[3] generates different code depending on whether x is an array or a pointer. Given the declarations above, when the compiler sees the expression a[3], it emits code to start at the location “a,” move three past it, and fetch the character there.  When it sees the expression p[3], it emits code to start at the location “p,” fetch the pointer value there, add three to the pointer, and finally fetch the character pointed to.  In the example above, both a[3] and p[3] happen to be the character 'l', but the compiler gets there differently.  (See also questions 17.19 and 17.20.)

Source: http://www.lysator.liu.se/c/c-faq/c-2.html

Offsets with pointers

Pointers will have different offsets depending on the exact type of the pointer. So if you make a pointer to an array using:

#include

int main()
{

 char a[10];
 scanf("%s", a);
 printf("%p\n%p\n", &a, &a + 1);

}

Try to guess the difference.

It’s not 1!

 

 

 

 

 

 

 

aneesh@mybaby:~$ ./point 
1234567
0x7ffede46e3b0
0x7ffede46e3ba

Its 10.

How is that? Well, &a is a pointer to an array, its not a pointer to a character, its a pointer to the full array. Yes it still contains the memory address of the start of the array, which is the first character, but the type of the pointer is char (*)[10] which is very different from char *

to be continued…