我还发现大多数继承示例都不太理想,但我提出了一个我认为很干净并且允许完全继承的解决方案。
由于服务和指令中没有可用的原型信息并且直接扩展 Object 并不好,您将需要创建一个可以包含常量或非常简单的通用逻辑的高级基类。
var BaseService = function() {};
BaseService.prototype.toast = "french";
BaseService.prototype.halloween = "scary";
接下来让我们创建一个可以扩展的抽象服务(指令的逻辑相同)。
module.factory('AbstractDirective', function(
$http, $q, $rootScope, $compile, $timeout) {
$.extend(this, new BaseService);
// Additional logic and methods should be appended onto 'this'
this.doStuff = function() {
alert("abstract function called");
};
this.halloween = 'fun';
// If adding a variable to the prototype of this extended class is desired
// then this function would need to be extracted to its own variable
// where the prototype values can be set before the function
// is passed to the factory.
return this;
}
现在让我们创建一个实际的实现:
module.directive('DirectiveImpl', ['AbstractDirective', function(AbstractDirective) {
$.extend(this, AbstractDirective);
// A great part about this implementation pattern is that
// DirectiveImpl does not need to pass anything to construct AbstractDirective.
// Meaning changes to AbstractDirective will have less impacts
// on implementing classes.
this.doStuff = function () {
// Call
AbstractDirective.doStuff();
// Implement some logic additional
alert(this.toast + "Toast\nHalloween is " + this.halloween );
}
return this;
}]);
供服务使用
module.factory
代替
module.directive
当 DirectiveImpl 调用 doStuff 函数时,您将收到 2 个警报:
abstract function called
然后
French Toast
Halloween is fun
可以遵循类似的模式来允许控制器的完全继承,但还有更多的工作要做。