Chris
Chris

Reputation: 652

AngularJS Factory Object Being Reference

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.

Upvotes: 0

Views: 45

Answers (1)

Karim
Karim

Reputation: 8632

_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

});

Upvotes: 1

Related Questions