I'm creating an angular factory that encapsulates and injectable type that can be new-ed up as such:
(function() {
angular
.module('app')
.factory('PaymentStream', [
function() {
function PaymentStream(){
this._endingBalance = null;
}
PaymentStream.prototype.serialize = function() {
// method body here
};
return PaymentStream;
}]);
})();
When I create a PaymentStream via new PaymentStream()
only the constructor seems to have been called. If I don't use prototype
and just define the methods inside the constructor it works but then I'm redefining the functions with each instance.
Any idea why those prototypes are not being set?
Edit
Here is how it is being used in the outside.
function addStreamFunctions(stream) {
angular.merge(stream, new PaymentStream());
}
So basing on your edit, The factory was indeed working correctly. The problem is the way you used it, you angular.merge
d the new
ed object with another object, so its type is not a PaymentStream
anymore, the resulting object became a 'generic' object
If the stream is a plain object, what you can do is pass the stream
variable in the constructor of PaymentStream
and do the merging manually inside your constructor function. Something like
function PaymentStream(stream){
this._endingBalance = null;
var keys = Object.keys(stream); //get all properties from the stream
keys.forEach(function(key){
this[key] = stream[key]; //put each one in the instance of your object;
});
}
then use it like
function addStreamFunctions(stream) {
var stream = new PaymentStream(stream);
}
this code is untested, please tell me if it worked or not :)
Since you are working with factory
you need to return an instance of the object, in this case a new instance of PaymentStream
(function() {
angular.module('my-app').factory('PaymentStream', [function() {
function PaymentStream() {
this._endingBalance = null;
}
PaymentStream.prototype.serialize = function() {
// method body here
};
return new PaymentStream();
}]);
})();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.