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 關注
- 530 瀏覽
添加回答
舉報
