AngularJS service inheritance

后端 未结 4 665
北海茫月
北海茫月 2020-12-28 09:14

I have next service:

angular.module(\'app\').service(\'BaseService\', function (alertService) {
   var service = {};
   service.message =  \"Hello\";
   serv         


        
4条回答
  •  不思量自难忘°
    2020-12-28 09:27

    I would modify a little bit your code:

    app.factory('BaseService', function () {
       //var service = {}; 
       function service(){
           this.message = "hello";
       }; 
       service.prototype.perform = function () {
            console.log('perfom', this.message);
       };
       return new service();
    });
    

    (I just change your alertService for an console.log();.. )

    then implement inheritance like this:

    app.factory('childBaseService',['BaseService', function(BaseService){
        var childBaseService = function(){
                BaseService.constructor.call(this)
                this.message = 'world!';
        };
    
        childBaseService.prototype = Object.create(BaseService.constructor.prototype);
        childBaseService.prototype.constructor = childBaseService;
    
        return new childBaseService();
    
    }]);
    

    You could see a example of how this works.. at the end, BaseService and childService would be instances of BaseService constructor ( service ).

    console.log(BaseService instanceof BaseService.constructor); //true
    console.log(childBaseService instanceof BaseService.constructor); //true
    

提交回复
热议问题