サービスとファクトリーの本質的な違いが何であるかを理解しようとしています(AngularJSで)。ファクトリはシングルトンであり、サービスは呼び出すたびに新しいオブジェクトであると言うのは本当ですか?
2 に答える
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
this.getColor = function()
{
return color;
}
}
Box をインスタンス化し、異なる色で初期化するには:
var blueBox = new Box("blue");
alert(blueBox.getColor()); // will alert blue
var greenBox = new Box("green");
alert(greenBox.getColor()); // will alert green
Box の例のようなコンストラクター関数を登録するには、angular サービスが使用されます。サービスが注入されると、サービスのインスタンスが関数に渡されます。
// 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'
});
対照的に、Angular ファクトリは関数のインスタンスを返しません。代わりに、関数を呼び出した結果をキャッシュして返します。
// 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.
};
ファクトリは、関数の結果を返す方法と考えてください。結果は、すべてのインジェクション間で共有されるシングルトンです。
サービスは、クラス (または関数コンストラクター) をインスタンス化する方法と考えてください。インスタンスもシングルトンであり、すべてのインジェクション間で共有されます。
ファクトリとサービスはどちらもシングルトンです。
サービスとファクトリの唯一の違いは、サービスが new で呼び出されることです。
stuffToInject = new Service();
一方、ファクトリは関数のように呼び出されます
stuffToInject = Factory();
それ以外の場合は同じです。ファクトリとサービスの両方がシングルトンです。自問する必要がある唯一の質問は、サービスに新しい演算子が必要かどうかです。そうでない場合はmodule.factory
、elseを使用しますmodule.service
。
例:
function(){
this.foo=function(){
}
}
module.service に登録する必要があります
function(){
return {
foo:function(){}
};
}
module.factory で登録可能