Angularjs 工厂/服务的本质
我试图理解服务和工厂之间的本质区别(在AngularJS中)。在javascript中,函数可以类似于一个类,它具有实例变量、实例方法,并且可以是新的:Angularjs 工厂/服务的本质,angularjs,factory,angularjs-service,angular-services,Angularjs,Factory,Angularjs Service,Angular Services,我试图理解服务和工厂之间的本质区别(在AngularJS中)。在javascript中,函数可以类似于一个类,它具有实例变量、实例方法,并且可以是新的: // creating a class Box function Box(col) { // instance member variable color, default to 'Red' if no color passed var color = col || 'Red'; // instance method
// creating a class Box
function Box(col)
{
// instance member variable color, default to 'Red' if no color passed
var color = col || 'Red';
// instance method
this.getColor = function()
{
return color;
}
}
要实例化长方体并使用不同的颜色初始化它,请执行以下操作:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
angular服务用于注册构造函数,如Box示例。注入服务时,服务的实例将传递到函数中:
// declare a service
app.service('box', Box);
// inject instance of Box into controller: 'box' is a new Box()
app.controller('ctrl', function(box) {
alert(box.getColor()); // alerts 'Red'
});
// declare a factory
app.factory('user', function() {
// return an object literal
return {
name: 'john',
}
});
app.controller('ctrl', function(user) {
alert(user.name);// user is the object literal which was returned from the user factory.
};
相反,角度工厂不返回函数的实例。相反,它缓存并返回调用函数的结果:
// declare a service
app.service('box', Box);
// inject instance of Box into controller: 'box' is a new Box()
app.controller('ctrl', function(box) {
alert(box.getColor()); // alerts 'Red'
});
// declare a factory
app.factory('user', function() {
// return an object literal
return {
name: 'john',
}
});
app.controller('ctrl', function(user) {
alert(user.name);// user is the object literal which was returned from the user factory.
};
将工厂视为返回函数结果的一种方式;结果是在所有注入之间共享一个单例
将服务视为实例化类(或函数构造函数)的一种方式;该实例也是一个单例,在所有注入之间共享
工厂和服务都是单件的。服务和工厂之间的唯一区别是服务被称为新的
stuffToInject = new Service();
而工厂只是被称为类似函数
stuffToInject = Factory();
否则就一样了,工厂和服务都是单件的。你需要问自己的唯一问题是我的服务是否需要新的操作员。如果不需要,请使用module.factory
,否则使用module.Service
例如:
function(){
this.foo=function(){
}
}
需要向module.service注册
function(){
return {
foo:function(){}
};
}
可以在模块中注册。工厂否。工厂是用于构建服务的功能。一个服务总是一个单独的个体。请参见我引用的
服务遵循工厂方法设计模式(每次注入都会创建一个新的函数实例)。
:否。服务和工厂都是单例的。服务不会在每次注入时创建新实例。