3 回答
TA贡献1793条经验 获得超6个赞
angular.service('myService', myServiceFunction); angular.factory('myFactory', myFactoryFunction);
服务
myInjectedService <---- new myServiceFunction()
工厂
myInjectedFactory <--- myFactoryFunction()
比如写一个 服务函数公开公共API:
function myServiceFunction() { this.awesomeApi = function(optional) { // calculate some stuff return awesomeListOfValues; }}--------------------------------------------------------------------------------- // Injected in your controller$scope.awesome = myInjectedService.awesomeApi();
或者使用 工厂函数公开公共API:
function myFactoryFunction() { var aPrivateVariable = "yay"; function hello() { return "hello mars " + aPrivateVariable; } // expose a public API return { hello: hello };}--------------------------------------------------------------------------------- // Injected in your controller$scope.hello = myInjectedFactory.hello();
或者使用 工厂函数返回构造函数:
function myFactoryFunction() { return function() { var a = 2; this.a2 = function() { return a*2; }; };}--------------------------------------------------------------------------------- // Injected in your controllervar myShinyNewObject = new myInjectedFactory();$scope.four = myShinyNewObject.a2();
用哪一个?.
var myShinyNewObject = new myInjectedService.myFunction()
var myShinyNewObject = new myInjectedFactory();
new()
还有一件事,他们都是单身.。
TA贡献1868条经验 获得超4个赞
// Serviceservice = (a, b) => { a.lastName = b; return a;};// Factoryfactory = (a, b) => Object.assign({}, a, { lastName: b });
const fullName = { firstName: 'john' };
// Service
const lastNameService = (a, b) => {
a.lastName = b;
return a;
};
console.log(lastNameService(fullName, 'doe'));
// Factory
const lastNameFactory = (a, b) =>
Object.assign({}, a, { lastName: b })
console.log(lastNameFactory(fullName, 'doe'));
- 3 回答
- 0 关注
- 491 浏览
添加回答
举报