Monthly Archives: March 2016

Javascript Functions, scoping, and changing context

Since no inner function is declared, this function object is bound to the global scope.

In the above code:

  • global scope has one variable globalVariable.
  • However in globalFunction function object, notice notice we have a inner function, and thus, each function’s this scope is bound to itself.
  • the inner function cannot read the outer scope’s variable and thus both innerVariable and globalVariables are undefined.
  • In globalFunction’s globalVariable is undefined because it is not declared in its this scope

Thus, in the example, there are separate ‘this’ objects bound to each invoking function.

Unbeknownst to many Javascript developers, there is an arguments object created within a function. It is an Array-like object (only having the property length). Arguments has three main properties, namely, callee (the invoking method), length, and caller (the reference to invoked function).

Declaring a variable arguments inside a function replaces/overrides the primary arguments object.

Call, Apply

Both call and apply are used to invoke a method on an object.


The bind method is used to invoke methods while explicitly specifying this.


mongo dump

Say you want to do a dump of your mongo database onto your desktop.

You’d go:

mongodump -d DumpFolderName -o /location/of/your/directory


Once it makes a dump, you’ll see the DumpFolderName folder with various files in there. It contains the data of your database.


When you want to make the restore, copy the DumpFolderName to that machine. Make sure MongoDB is installed. Then just type

mongorestore DumpFolderName


Private methods in Objective C are semi private

ref –

A word about usage

When implementing a class, it is common to have a set of methods that only appear in the class’s @implementation. Often, they are spread around the @implementation and generally appear just above whatever method first uses the private method (if they were to appear below, the compiler will warn).

Eventually, this becomes unwieldy and the developer will capture the private method’s declarations into a category declaration at the top of the implementation file. Something like:

The resulting problem is that the compiler will not check to make sure you have implemented all of the methods declared in that category. Nor will it catch, say, spelling errors in the method declarations in the implementation.

This is because a category with no corresponding implementation is an informal protocol in Objective-C. It is a set of method declarations that can optionally be implemented, often on a subclass of the class with the category declaration.

Because a class extension effectively extends the class’s primary interface, changing the above declaration to the following makes the declared methods have the same requirements as methods declared in the class’s oft public primary interface.


One common complaint for many new to Objective-C is that the language lacks support for private methods within a class. There are compiler directives for instance variables: @private, @protected (the default) and @public. link

However, if you want to hide methods, there is no specific directives to help.

The Problem

Using private methods, we can generally hide the details or behaviors of a class from other classes. These other classes may be clients, Categories, or subclasses.

Compile-time private methods are supported; if a class doesn’t declare a method in its publicly available interface, then that method might as well not exist as far as your code is concerned.
In other words, you can achieve all of the various combinations of visibility desired at compilation time by organizing your project appropriately.

For example:

To avoid exposing a method as part of a class’s API, we do not declare it within the @interface section but within the @implementation section.

makeActivationSound is current exposed. Let’s say we want to make this private, and not let others access this method. We so by removing it from the interface Lightsaber, and put it either in the “private extension” of the Lightsaber class, or simply just declare it as a method within the implementation file.

Now, a private method like makeActivationSound can no longer be called by another class. A method call from a Jedi class like:

is no longer possible.

Compiler error: Method ‘makeActivationSound’ is defined in class
‘Lightsaber’ and is not visible.

Methods are semi private in Objective C

using performSelector to call private methods

Although if we use the performSelector method or the Objective-C Runtime library, we can still invoke private methods.
switchOn is the public method, which calls the private method makeActivationSound of the LightSaber class.
From ViewController, by using performSelector, we still able to manage the private method.


The result would be:


Hence there is no true private methods in Objective C.

Using subclasses to access private method

When child classes access the Lightsaber public method switchOn, it will access Lightsaber private method makeActivationSound.

Extending the base class

So say another developer comes in and want to extend the Lightsaber class into a child class called DoubleBladedLightsaber

The developer wants to over-ride the switchOn behavior, and therefore calls [super switchOn]. Then, he wants to add an additional functionality so he declares his own private method. And calls it right after using the base class’s switchOn.


[[DoubleBladedLightsaber new] switchOn];

What he gets is:


The 1st BB-ZSHUUUU is from [super swithcOn]. The switchOn in the base class then calls makeActivationSound. However, it sees that the child class have over-ridden its makeActivationSound, and thus, uses the child’s makeActivationSound method. This results in the output BB-ZSHUUUU, and not BB-ZSHOOOO.

The 2nd BB-ZSHUUUU is just a call to its own private method makeActivationSound. THEREFORE:

Private methods in Objective-C are not as private as in other modern object-oriented programming languages. They are semi-private and have polymorphic behavior.

In objective C, we can (accidentally) compromise the implementation of our extended class. The probability of unknowingly overriding a private method rises when we extend a framework or library class without having access to its source code.

To reduce the risk of accidental method overriding, we should add a prefix to the names of private methods that is as unique as possible.

For this reason, one should use an uppercase abbreviation of the company and/or the product name. In our example that could be the prefix AQN_LS_ for the company akquinet and the product Lightsaber:

After this modification, the [super switchOn] will access its own class’s private method.

So, the risk of accidentally overriding a private method depends on the uniqueness of its name.

  • As private methods can be overridden in Objective-C, there is a risk of compromising the implementation of an extended class.
  • Therefore, always use an application-specific unique prefix for the names of private methods.
  • A single underscore character (_) may not be used as a prefix, as this is reserved for Cocoa classes.

iOS interview questions

NSUserDefaults (store only user settings)

NSUserDefaults is really meant for storing small pieces of data such as settings, preferences, and individual values.
It’s pretty fast and easy to do, though it’s supposed to store only user settings. To write them to the userdefaults:

To read the from the userdefaults:

NSUserDefaults is thread safe. However, NSUserDefaults “thread-safeness” seems to come from running operations on the main-thread.

Protocol vs KVO

Protocol is a one to one relationship where a receiving object implements a delegate protocol. A sending object uses it and sends messages (assuming that those methods are implemented) since the receiver promised to comply to the protocol.

KVO is many-to-many relationship where one object could broadcast a message and one or multiple other objects can listen to it and react.

How and where would you use UKIT’s classes?

UIKit classes should be used only from an application’s main thread. Note: The derived classes of UIResponder and the classes which manipulate application’s user interface should be used from application’s main thread.

What is MVC? How is it implemented in iOS? What are some pitfalls you’ve experienced with it? Are there any alternatives to MVC?

MVC stands for Model, View, Controller. It is a design pattern that defines how to separate out logic when implementing user interfaces. In iOS, Apple provides UIView as a base class for all Views, UIViewController is provided to support the Controller which can listen to events in a View and update the View when data changes. The Model represents data in an application and can be implemented using any NSObject, including data collections like NSArray and NSDictionary.

Some of the pitfalls that people hit are bloated UIViewController and not separating out code into classes beyond the MVC format. I’d highly recommend reading up on some solutions to this:

On a UITableViewCell constructor:

– (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
What is the reuseIdentifier used for?

The reuseIdentifier is used to indicate that a cell can be re-used in a UITableView. For example when the cell looks the same, but has different content. The UITableView will maintain an internal cache of UITableViewCell’s with the reuseIdentifier and allow them to be re-used when dequeueReusableCellWithIdentifier: is called. By re-using table cell’s the scroll performance of the tableview is better because new views do not need to be created.

In other words, the reuseIdentifier is used to group together similar rows in an UITableView; i.e., rows that differ only in their content, but otherwise have similar layouts.

A UITableView will normally allocate just enough UITableViewCell objects to display the content visible in the table. If reuseIdentifier is set to a non-nil value, then when the table view is scrolled, UITableView will first attempt to reuse an already allocated UITableViewCell with the same reuseIdentifier. If reuseIdentifier has not been set, the UITableView will be forced to allocate new UITableViewCell objects for each new item that scrolls into view, potentially leading to laggy animations.

Explain the difference between atomic and nonatomic synthesized properties?

Atomic and non-atomic refers to whether the setters/getters for a property will atomically read and write values to the property.

When the atomic keyword is used on a property, any access to it will be “synchronized”. Therefore, a call to the getter will be guaranteed to return a valid value, however this does come with a small performance penalty.

Hence in some situations nonatomic is used to provide faster access to a property, but there is a chance of a race condition causing the property to be nil under rare circumstances (when a value is being set from another thread and the old value was released from memory but the new value hasn’t yet been fully assigned to the location in memory for the property).

Explain the difference between copy and retain?

Retaining an object means the retain count increases by one. This means the instance of the object will be kept in memory until it’s retain count drops to zero. The property will store a reference to this instance and will share the same instance with anyone else who retained it too. Copy means the object will be cloned with duplicate values. It is not shared with any one else.

What is a category and when is it used?

A category is a way of adding additional methods to a class without extending it. It is often used to add a collection of related methods. A common use case is to add additional methods to built in classes in the Cocoa frameworks. For example adding async download methods to the UIImage class.


All UI updates must be done on the main thread. In the code above the update to the alert text may or may not happen on the main thread, since the global dispatch queue makes no guarantees . Therefore the code should be modified to always run the UI update on the main thread

Difference between [self method] or performSelector@selector(method)?

Thus even though these are equivalent:

The second form allows you to do this:

Difference between strong and retain ?

Its entirely semantic to the way ARC and non-ARC projects work. Apple would prefer everyone use ARC and is pushing in that direction.

In a non-ARC project “strong” will act as “retain”. In an ARC project “retain” might work if clang doesn’t flag an error (i dont use ARC), but theres a subtlety in the description.

Retain says – Im holding on to this object, until Im ready to release it, strong says (hey ARC treat this as a retained object and insert some generated code in my dealloc method to be released when the autorelease pool drains).

strong is a new feature in iOS 5 Automatic Reference Counting (ARC) which behave the same as retain in iOS 4

What is the difference between retain & assign?

Assign creates a reference from one object to another without increasing the source’s retain count.

Retain creates a reference from one object to another and increases the retain count of the source object.

Sending file from html to node server (multer)

node server download

ref –

client side

Server side – index.js

Make sure you create the folder Images at the the directory your index.js is at.

However, our solution always jumps to another page.
In order to do it without any jump, we do it without a form

non-form way

First, we create a file uploader, and button control

For the button, whenever we press it, we will run function uploadImage
In this function, we first get the file object via the files property. The files property is an array, and we simply get the first element.

Once we have this file, we create a FormData object, append our file to it. Make sure to call it “imgUploader” as that’s what our multer code from the server side is expecting.

Assign the form data object to body and that’s it.

Javascript Prototype

Prototype, function, and New

When you call a function with new, four things happen under the hood:

  • A new object gets created (let’s call it O)
  • O gets linked to another object, called its prototype
  • The function’s this value is set to refer to O
  • The function implicitly returns O

We can also rewrite our Food function to work without the new keyword:

Everything is straightforward, except the setPrototypeOf.

Prototype Inheritance

Under normal circumstances, all objects in JavaScript — including Functions — are linked to another object, called its prototype.

If you request a property on an object that the object doesn’t have, JavaScript checks the object’s prototype for that property. In other words, if you ask for a property on an object that the object doesn’t have, it says: “I don’t know. Ask my prototype.”

This process — referring lookups for nonexistent properties to another object — is called delegation.

The output from our toString calls is utterly useless, but note that this snippet doesn’t raise a single ReferenceError!
That’s because, while neither joe or sara has a toString property, their prototype does.

When we look for sara.toString(), sara says, I don’t have a toString property. Ask my prototype.
JavaScript, obligingly, does as told, and asks Object.prototype if it has a toString property. Since it does, it hands Object.prototype’s toString back to our program, which executes it.

It doesn’t matter that sara didn’t have the property herself — we just delegated the lookup to the prototype.

In other words, we can access non-existent properties on an object as long as that object’s prototype does have those properties. We can take advantage of this by assigning properties and methods to an object’s prototype, so that we can use them as if they existed on the object itself.

Even better, if several objects share the same prototype — as is the case with joe and sara above — they can all access that prototype’s properties, immediately after we assign them, without our having to copy those properties or methods to each individual object.

This is what people generally refer to as prototypical/prototypal inheritance — if my object doesn’t have it, but my object’s prototype does, my object inherits the property.

In reality, there’s no “inheritance” going on, here.

In class-oriented languages, inheritance implies behavior is copied from a parent to a child.

In JavaScript, no such copying takes place — which is, in fact, one of the major benefits of prototypes over classes because we can dynamically switch to different prototypes and the prototype would “delegate” properties to those objects.

Setting an Object’s Prototype

The function, Object, has a property, called .prototype, which points to any object Object.prototype that you want.

The object, Object.prototype, has a property, called .constructor, which points to a function (Object). Keep in mind that this Object.prototype.constructor property is just a public property of Object.prototype. It is not used in any way in the construction of new objects or resolution of property names.


You can also change the property to reference other objects. Rabbit.Property references an object. Any object created with new will now have their [[Prototype]] reference object {eats: true}. When we change Rabbit.Property to an empty object {}, further new objects created will then have their [[Prototype]] reference the new prototype object.


Prototype properties will over shadow objects that delegate from them

When both your object and its prototype has the same property, the prototype will have precedence.

Now we add the function “cook” to our prototype, in which we can then use.

Further Reading – Prototype Chain Details

In programming, we often want to take something and extend it.

In JavaScript, objects have a special hidden property [[Prototype]] (as named in the specification), that is either:
– null
– references another object. (all properties/methods of that object will be inherited)

That object is called “a prototype”:

When we want to read a property from object, and it’s missing, JavaScript automatically takes it from the prototype.

The property [[Prototype]] is internal and hidden, but there are many ways to set it.
One of them is to use __proto__, like this:

// So if animal has a lot of useful properties and methods,
// then they become automatically available in rabbit.
// Such properties are called “inherited”.

__proto__ IS NOT the same as [[Prototype]].

[[Prototype]]’s getter/setter is __proto__

If the subclass does not have the property/method, then JavaScript automatically takes it from the parent class.

Then, when console.log tries to read property rabbit.eats (**), it’s not exist in rabbit, so JavaScript follows the [[Prototype]] reference and finds it in animal (look from the bottom up).

Here we can say that animal is the prototype of rabbit or rabbit prototypally inherits from animal.

So if animal has a lot of useful properties and methods, then they become automatically available in rabbit. Such properties are called “inherited”.

Inherited Method

If we have a method in animal, it can be called on rabbit:

Longer Prototype Chain

getter setter in prototype inheritance

An interesting question may arise in the example above: what’s the value of this inside set fullName(value)?
Where the properties and this.surname are written: user or admin?
The answer is simple: this is not affected by prototypes at all.
No matter where the method is found: in an object or its prototype. In a method call, this is always the object before the dot.
So, the setter actually uses admin as this, not user.

That is actually a super-important thing, because we may have a big object with many methods and inherit from it.
Then we can run its methods on inherited objects and they will modify the state of these objects, not the big one.

For instance, here animal represents a “method storage”, and rabbit makes use of it.
The call rabbit.sleep() sets this.isSleeping on the rabbit object:

If we had other objects like bird, snake etc inheriting from animal, they would also gain access to methods of animal. But this in each method would be the corresponding object, evaluated at the call-time (before dot), not animal. So when we write data into this, it is stored into these objects.

As a result, methods are shared, but the object state is not.

In JavaScript, all objects have a hidden [[Prototype]] property that’s either another object or null.

We can use obj.__proto__ to access it (there are other ways too, to be covered soon).

The object referenced by [[Prototype]] is called a “prototype”.

If we want to read a property of obj or call a method, and it doesn’t exist, then JavaScript tries to find it in the prototype list, from its immediate parent, and on up.

Write/delete operations work directly on the object, they don’t use the prototype (unless the property is actually a setter).

If we call obj.method(), and the method is taken from the prototype, the obj’s “this” still references the obj. So methods always work with the current object even if they are inherited.


rabbit.jumps overrides its prototype reference’s jumps. Thus we get true.
Then we delete rabbit.jumps. This deletes the rabbit’s jumps (the one that overrides the prototype’s jumps).
Since the jump that overrides the prototype’s jump is now deleted, “rabbit.jumps” then refers to its prototype’s jumps, which comes out to be null.
We delete animal.jumps.
Since rabbit has no jumps, and then it goes to its prototype and sees no jumps, then jumps would be undefined, because undefined is assigned to anything that is undeclared.

Including Prototype, properties that describe the state of a particular object, is written into the object

Speedy derives from hamster.
lazy derives from hamster.
Stomach, since it is a property that describes the state of an object, is written into itself.
Thus, that’s why when Speedy calls stomach, it does this:

1) accesses this.stomach, stomach here belongs to hamster.
2) calls push on this.stomach. It pushes a string into array stomach.

When Lazy calls stomach, it does the same thing as above.

Thus, that’s when a parent class has a property that describes the state of an object, all its deriving objects will share that property.

In order to fix this you can do 2 things:

Essentially, we work on “this”, the child object that is deriving.
Then, we create a new array with the food name, and references the child object’s property to it.

2) Instead of working on “this” in the parent object, we simply put all methods to be shared by “this” in the parent object, and leave the stomach property for its children like so:

__proto__ and prototype usage

setting JAVA environment variable

Windows 8

1) First install Java onto your machine

2) You then have to set your environment variable JAVA_HOME to be the location where the bin directory of all the .dlls and .exes are.

Right click the windows icon on the very bottom left. Select System

Click on the Environmental variable button. And look for the JAVA_HOME variable. If its there, edit it. If its not, click on ‘New’, and create the JAVA_HOME variable.

The Variable value is where the location is. What we’re looking for is the location to the bin folder where all the .exe and .dll are. Hence, after you install Java, its usually somewhere in C://Program Files/Java/JRE_x.xx.xx/.

In our case, if you start from the C directory, find Program Files, then find Java. In my case, I found it at C:\Program Files (x86)\Java\jre1.8.0_73

Thus, you just paste that into the environment variable.


3) you then have to add the directory location of the PATH variable. When you see it, click edit, and then go to the end of the string. Then type in:

;C:\Program Files (x86)\Java\jre1.8.0_73

notice the semi-colon. this is to separate this entry from the other entries.


APN server notes

To insert device

db.deviceCollection.insert({ “device_id” : “f0bafec6 be2a9e1a c31c9cb0 8c6589df 0bc1a7c4 ac9d7767 e63b7656 07c62145”, “bundle_id” : “com.rtsao.localapn”, “description” : “yes” })