A class that has an array and getter/setter.
var MyObject = (function MyObject() {
this.arr = [];
MyObject.prototype.addArr = function(i) {
this.arr.push(i);
};
MyObject.prototype.getArr = function() {
return this.arr;
};
});
And another object try to access to array of MyObject.
var AnotherObject = (function AnotherObject() {
AnotherObject.prototype.addToMyObject = function(i, MyObject) {
MyObject.addArr(i); // here's the problem!
};
AnotherObject.prototype.getArr = function(MyObject) {
return MyObject.getArr();
};
});
Now test.
var a = new MyObject();
a.addArr(1);
a.addArr(2);
a.addArr(3);
// works good.
console.log(a.getArr().pop()); // 3
console.log(a.getArr()); // [1,2]
var b = new AnotherObject();
b.addToMyObject(4);
b.addToMyObject(5);
b.addToMyObject(6);
console.log(b.getArr().shift()); // error!
console.log(b.getArr());
It says AnotherObject.addToMyObject() is wrong. 'addArr' is not defined or null inside of addToMyObject().
Correct me how to access another Object's variable
MyObjectinstance intoaddToMyObjectwhen invoking it, it's expecting this as the second argument