An AngularJS factory for simple class based inheritance with support for mixins
An AngularJS factory for simple class based inheritance with support for mixins
this._super('methodName', arguments)
to call super class methodsthis
context in super()
callsmixins: []
npm i angular-base-class --save
bower install angular-base-class --save
BaseClass
as dependency to your AngularJS app
angular.module('App', ['BaseClass'])
.factory('Mammal', ['BaseClass', function (BaseClass) {
return BaseClass.extend({
setAge: function (age) {
this.age = age;
},
getAge: function () {
return this.age;
}
});
}])
.factory('Dog', ['Mammal', function (Mammal) {
return Mammal.extend({
setAge: function (age) {
this._super('setAge', age + 10);
},
getAge: function () {
return 'Dog is ' + this._super('getAge') + ' years old';
}
})
}])
.controller('Ctrl', ['$scope', 'Dog', function ($scope, Dog) {
$scope.dog = new Dog({age: 5});
$scope.dog.getAge(); // Dog is 5 years old
$scope.dog.setAge(8);
$scope.dog.getAge(); // Dog is 18 years old
}]);
angular.module('App', ['BaseClass'])
.factory('Mammal', ['BaseClass', function (BaseClass) {
return BaseClass.extend({
constructor: function (args) {
this.age = args.age + 1;
},
setAge: function (age) {
this.age = age;
},
getAge: function () {
return this.age;
}
});
}])
.factory('Dog', ['Mammal', function (Mammal) {
return Mammal.extend({
constructor: function () {
this._super('constructor', arguments);
},
setAge: function (age) {
this._super('setAge', age + 10);
},
getAge: function () {
return 'Dog is ' + this._super('getAge') + ' years old';
},
})
}])
.controller('Ctrl', ['$scope', 'Dog', function ($scope, Dog) {
$scope.dog = new Dog({age: 5});
$scope.dog.getAge(); // Dog is 6 years old
$scope.dog.setAge(8);
$scope.dog.getAge(); // Dog is 18 years old
}]);
angular.module('App', ['BaseClass'])
.factory('mammalMixin', [function () {
return {
grow: function (number) {
this.age += number;
},
getName: function () {
return this.name;
}
};
}]);
.factory('Mammal', ['BaseClass', 'mammalMixin', function (BaseClass, mammalMixin) {
return BaseClass.extend({
constructor: function (args) {
this.name = args.name;
this.age = args.age;
},
setAge: function (age) {
this.age = age;
},
getAge: function () {
return this.age;
},
mixins: [mammalMixin]
});
}])
.factory('Cat', ['Mammal', function (Mammal) {
return Mammal.extend({
getAgeAndName: function () {
return 'Age: ' + this.getAge() + ' Name: ' + this.getName();
}
});
}])
.controller('Ctrl', ['$scope', 'Cat', function ($scope, Cat) {
$scope.dog = new Cat({name: 'Meow', age: 5});
$scope.dog.getAge(); // 5
$scope.dog.setAge(8);
$scope.dog.getAge(); // 8
$scope.dog.getName(); // Meow
$scope.dog.getAgeAndName(); // Age: 8 Name: Meow
$scope.dog.grow(2);
$scope.dog.getAge(); // 10
}]);
npm install
npm run test
Licensed under the MIT license. Copyright (c) 2015 - 2017 Audrius Jakumavicius