0

I create a AngularJS factory following the tutorial of

https://medium.com/opinionated-angularjs/angular-model-objects-with-javascript-classes-2e6a067c73bc

The problem is, a new object is not being created and the value got updated to previous object, here is my code

let t1 = new Transaction({
  id : '123'
})
let t2 = new Transaction({         
  id : '1234'
})

console.log(t1.getId()) // Suppose to get 123 but getting 1234
console.log(t2.getId()) // Getting 1234

Here is my factory:

.factory('Transaction',function(){
    let _data = {};

    Transaction.prototype.getId = getId


    function Transaction(params) {                 
        _data.id = params.id ? params.id : '';

    }

    function getId() {
        return _data.id;
    }

    return Transaction

});

Under t1.getId() I suppose to be getting '123' but I'm getting '1234' instead.

1
  • I don't think you need to initialise it as a class. Factories are singletons, as long as you inject it, you can just access its methods, variables: let t = Transactions.getId() Commented Oct 24, 2018 at 12:09

1 Answer 1

1

_data is a shared object between the two instances of Transaction, it's behaving exactly as it should, every time you instantiate a new Transaction the id is overriding the previous, and you will always end up with the last one.

To get what is supposed to be the desired behaviour make _data an instance field.

factory('Transaction',function(){

    Transaction.prototype.getId = getId


    function Transaction(params) {
        this.data = {};                
        this.data.id = params.id ? params.id : '';

    }

    function getId() {
        return this.data.id;
    }

    return Transaction

});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.