Similarities between Services and Factories in Angular JS – Part 1


Most of the articles talk about differences.I will start with similarities and work our way to differences.

I will be using the code added https://github.com/abhikmitra/Service-vs-Factory/tree/master/app/scripts .

So firstly we have 3 pages with 3 separate controllers.

1.MainCtrl,

2.AnotherCtrl,

3.OnemoreCtrl

Claim 1 : Services and factory are both lazy loaded.

Proof : Move from “another page” to “main page” and only then you will see customFactory, Customservice getting instantiated.

Claim 2: Both of them are singleton and can be accessed in the same way
ServiceOrFactorName.somefunction();
Proof:

Our Service look like


angular.module('serviceVsFactoryApp')
 .service('Customservice', function Customservice() {
 console.log("CustomService has been Called");
 console.warn("Value of this inside a factory",this,"Notice the __proto__ by putting a break point")
 var localVariable = 1;
 this.thisVariable = 100;
 this.test = function () {

 return ++localVariable;
 }
 });

This allows us to call the service from controller with the following syntax.

</pre>
Customservice.test();
<pre>

So what does angular internally do ? It does a new of the contructor function Customservice() and caches it for it to be used as a singleton .If you put a breakpoint in the customservice and check the value of this you will see

this.__proto__ = Customservice

Now if we want the same functionality form the factory,this is what we will be doing.

</pre>
angular.module('serviceVsFactoryApp')
    .factory('customFactory', function () {

        console.log("CustomFactory has been Called")
        var localVariable = 1;
        console.warn("Value of this inside a factory",this,"Notice the $get")

        return {
            test: function () {
                console.warn("Value of this inside the object a factory",this,"Notice the __proto__")
                return ++localVariable;
            },
            thisVariable : 100
        };
    })
<pre>

So for the first time when the service is instantiated customFactory function is invoked once. and the returned object is cached for the lifetime of the app.Hence we can access the test function in the same was as previously.
Putting a break point in the code ,you will see that the this operator has a $get which basically means that the factory function is the function that we pass it to the provider using $get.

Another way to achieve the same goal is through this way

</pre>
angular.module('serviceVsFactoryApp')
    .factory('customFactoryThatInstantiatesAfunction', function () {

        console.log("CustomFactory has been Called")
        var localVariable = 1;
        console.warn("Value of this inside a factory",this,"Notice the $get")
        function Customservice() {
            console.log("CustomService has been Called");
            console.warn("Value of this inside a factory", this, "Notice the __proto__ by putting a break point")
            var localVariable = 1;
            this.thisVariable = 100;
            this.test = function () {

                return ++localVariable;
            }
        }
        return new Customservice();
    })
<pre>

This is exactly what a service does.So a service is a syntactic sugar on top of factory which itself is a syntactic sugar on providers

Some of the similarities.
Both the service and factory can have private variables in our case we call it local variables.
In your controller ,you can choose to do this

</pre>
<pre>customFactory.addingRandom="random text"; Customservice.addingRandom="random text";</pre>
<pre>

Which basically adds a prototype to the current instance.And since its a singleton,all the modules using this instance get access to the value.

So this brings the part 1 to close. In part 2 we will see more of differences than similarities.

Advertisements

Functions Expression vs Declaration


Declaring functions might seem to be trivial but in the world of Javascript,there are a lot of misconceptions around it .I will try and demistify about what exactly goes on .

1.We will start off with this code snippet.


var fn = function(){
exprFn();
declaredFn();
var exprFn = function(){
console.log("Expression Function ran");
}
function declaredFn(){
console.log("Declared Function ran")
}
}
fn();

Does this work ? No . It says exprFn is undefined.
Conclusion:The reason being even though the variable declaration is hoisted at the top.The expression assigning the function to exprFn did not and hence we are trying to invoke undefined() and hence it is throwing an error.Lets correct it,which will take us to our next point.


2.


var fn = function(){
declaredFn();
var exprFn = function(){
console.log("Expression Function ran");
};
exprFn();
function declaredFn(){
console.log("Declared Function ran")
}
}
fn();

The result is

Declared Function ran
Expression Function ran
declaredFn() apparently was invoked before it was even declared.
Conclusion:This is because function declarations like variable get hoisted.Hence the declaredFn’ s declaration statement was hoisted and hence declaredFn was already declared.function declarations are parsed and evaluated before any other expressions are. Even if declaration is positioned last in a source, it will be evaluated foremost any other expressions contained in a scope


 

3.


var fn = function(){
declaredFn();
test();
var exprFn = function test(){
console.log("Expression Function ran");
};
exprFn();
function declaredFn(){
console.log("Declared Function ran")
}
}
fn();

We have changed the function a bit .We basically have named the anonymous function assigned to exprFn to test.It is called a named function expression.But the above code doesn’t work.
ReferenceError: test is not defined
As named function expression are also not hoisted.


 

4.


var fn = function(){
var exprFn = function test(){
console.log("Expression Function ran");
console.log("inner:expression",typeof exprFn)
console.log("inner:function name",typeof test)
};
exprFn();
console.log("outer:expression",typeof exprFn);
console.log("outer:function name",typeof test);
}
fn();

If you run the above piece of code you will see
Expression Function ran
inner:expression function
inner:function name function
outer:expression function
outer:function name undefined
So you see ,the function identifier (name) is not accessible by the outer scope.The specs says that the identifier should not be available in the scope enclosing it.Hence “test” is undefined

Now that we know the difference between function expression and function declaration.The question we will try and answer is

why the following doesn’t work as an IIFE: function foo(){ }();.

It doesn’t work because brackets after a function declaration doesn’t invoke the function.The function can only be immediately invoked if its an expression.


1+function foo(){console.log("I got executed");}()

The result is
I got executed
NaN
The spec says that the plus operator expects 2 expression.Hence our function declaration is transformed into a function expression and the extra brackets at the end invoke them.Similarly the common practice of using IIFE is putting it within brackets.


(function (){console.log("I got executed");})()

The extra brackets just turns the function declaration into an expression and makes it invokable.You can transform your function declaration to an expression by putting it in an operator that expects expression.Js would do the rest for you 🙂

Instance Creation Part 3


The previous post we dealt with how “new” works. In this post we will talk about how Object.create works.


var constructorObj = { a:1};
var obj = Object.create(constructorObj)

If we print obj, we will see Object {a: 1}

Firstly, obj is of type Object and not constructorObj.Secondly lets go a little deeper and try


Object.getPrototypeOf(obj)

Object {a: 1}

So basically the constructorObj got attached to the prototype of the new object.That is all it does

Now lets change our constructorObj


constructorObj.a = 2

print obj
Object {a: 2} .So the prototype shares the same object.Any value you change on the object also reflects on the instances.And also obj.constructor points to the native Object

Lets see how it behaves with instances created with new


var constructorFn = function(){this.a=1};
constructorFn.prototype.field1 = "test";
var obj = new constructorFn()
var newObj = Object.create(obj);

Now if we print newObj.We will see

Object {a: 1, field1: “test”}

So the way this happens is newObj[[prototype]]==obj,obj[[prototype]] = constructorFn[[prototype]].

So now if we print Object.getPrototypeOf(Object.getPrototypeOf(newObj)); we will see exactly what we expect Object {field1: “test”} .

Lastly lets see what happens when we pass a function


var obj = Object.create(constructorFn)

If we print obj , we will see Function {}
typeof obj is “object”
obj instanceof Function //true

So what exactly happens ? Well the function gets attached to the prototype .
Object.getPrototypeOf(obj) gives us the original constructorFn. Unlike new there is no change of the this object and hence obj does not get a copy of the properties.

Instance creation part 2


My previous post shows how instance creation works with new operator.So in this post we will try to deduce what really goes on.
We will start with the basic and try and go deep


var constructorFn = function(){this.a=1};
var obj = new constructorFn();
obj instanceof constructorFn // true

Nothing unusual here.When the new keyword is encountered ,the “this” is said to the current object itself and the key value pair is set on the object.

Lets now modify our code a bit


var constructorFn = function(){
this.a =1 ;
}
constructorFn.prototype.key1 ="value1";
constructorFn.prototype.key2 ="value2";

on printing obj we see

constructorFn {a: 1, key1: "value1", key2: "value2"}

So what exactly did happen ? We already understand how a came into the picture.
To understand how the other 2 property came in ,look at the below piece of code

Object.getPrototypeOf(obj);
//displays
Object {key1: "value1", key2: "value2"}

So the algorithm of obj = new fn() goes as follows
1.Execute fn.
2.If “this” is encountered,set its value to the current object
3.If a primitive value is returned then ignore that and set obj to point to the current object
4.If a complex object is returned then obj should ignore the current object and instead be set to the returned value.
5.obj[[prototype]] should now point to fn[[prototype]]

An important thing to understand is that __proto__ and prototype is not same.In the above example


( new Foo ).__proto__ === Foo.prototype ;//true
( new Foo ).prototype === undefined ;//true

__proto__ is the actual object that is used in the lookup chain to resolve methods, etc.Prototype is a property belonging only to functions. Used in case the function happens to be used as a constructor

PS:__proto__ is deprecated and Object.getPrototypeOf should be used.

So the last question remains as to what is the “constructor”.constructor is nothing but the function that constructed the object.

obj.__proto__ === obj.constructor.prototype //returns true
Object.getPrototypeOf(obj) === obj.constructor.prototype //returns true

Why was the last line necessary ? So that we understand that “prototype” is for functions and Object.getPrototypeOf() is for instances.

PPS: Object.getPrototypeOf(obj) === Object.getPrototypeOf(obj.constructor)//returns false .

The reason being getPrototypeOf internally checks the __proto__ property as that is how the chain is traversed and not prototype and hence constructorFn.key1 will be undefined.