gpt4 book ai didi

javascript - 服务的传承

转载 作者:行者123 更新时间:2023-12-03 06:48:27 25 4
gpt4 key购买 nike

我有以下模块:

angular.module('project.itemServices', ['project.cacheFactory', 'project.dataProvider'])

.run(function() {
ISvc = new function () {
this.endpoint = '';
this.name = 'foo';
this.items = {};
this.clean = function () {
cacheFactory.clear(this.name);
items = {};
};
this._store = null;
this.populate = function () {
cacheFactory.look('fetch', this.endpoint, this.name).then(function (data) {
this._store(data);
})
};
};
}
)

.service('catListSvc', function()
{
this.prototype = ISvc.prototype;
})

.run(function(catListSvc)
{
console.log(catListSvc.name);
});

我希望此模块中的所有服务都继承自 ISvc 对象,然后实现它自己的 _store 方法,该服务旨在在 Controller 之间共享数据。

我不知道该怎么做,当尝试console.log(catListSvc.name)时,出现undefined

我尝试了几件事,例如。 Objects.create(ISvc.prototype),但不起作用。

知道如何实现这一目标吗?

最佳答案

服务继承的基本模式可以分布在多个 JS 文件中,只需要 Angular DI

// service is PascalCased and returns a constructor
function BaseProjectService(...deps...) { ... }

app.value('BaseProjectService', BaseProjectService);

// service is camelCased and returns an instance
app.factory('someProjectService', ['BaseProjectService', ...deps..., function (BaseProjectService, ...deps...) {
function SomeProjectService(...deps...) {
// is a super constuctor, since SomeProjectService has got no own prototype
this.constructor(...deps);
...
}
SomeProjectService.prototype = BaseProjectService.prototype;
return new SomeProjectService(...deps...);
}]);

缺点是工厂函数而不是类负责 deps 注释和注入(inject),这会导致 WET 代码

当子服务需要自己的原型(prototype)时,这种模式可能会变得更加复杂,这是应该考虑 ES6 类的地方。

关于javascript - 服务的传承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37615371/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com