Search code examples
javascriptangularjssingletonprototypeangularjs-service

javascript pattern used in angular


I followed a AngularJS tutorial on http://www.tutorialspoint.com/angularjs/angularjs_services.htm

The method passed to CalcService service got me confused. Is Angular using revealing prototype or a different one. I was confused because that inner function declared in this.square should be private and not visible outside the context of the object. How Angular is able to access square.

mainApp.service('CalcService', function(MathService){
            this.square = function(a) { 
            return MathService.multiply(a,a); 
         }
});

Solution

  • Above answers does good explanation how service work but they don't explained how this which is newly created object is exposed.

    Whenever you create a service angular create a new object of that function for you, and that's get return whenever its get inject in controller, directive, service, etc. Internally method uses prototype of function to create an this which is context of function. Lets look at below code how it work internally.

    function CalcService(){
        //The line below this creates an obj object.
        //obj = Object.create(CalcService.prototype)
        //this = obj;
        //`this` is nothing but an instance of function/CalcService.prototype which is giving access to its property attached to this
        var privateVariableExample = 'test'; //this is private variable of service.
        this.square = function(a) {
            //return multiplacation result from here 
        }
    
        //return this;
    }
    
    var objectOfCalcService = new CalcService();
    objectOfCalcService.square(1);