badger
badger

Reputation: 17

How Can I Access private method of other object (but it's same instanceof) in Javascript

var a1 = new A("test")
var a2 = new A("test2")
console.log(a2.getOtherValue(a1)) // -> expected "test"
a2.setOtherValue(a1, "test3") // set another object value
console.log(a1.getValue()) // -> expected "test3"

How Can I implement this??

Upvotes: 0

Views: 33

Answers (1)

Rajesh
Rajesh

Reputation: 24915

You can use getter and setter methods to create a property and on add, you can mutate own value. Mutating other object using current object is a bad idea.

Following is a sample:

function MyNumber(value) {
  var _value = value;

  Object.defineProperty(this, 'value', {
    get: function() {
      return _value;
    },
    set: function(v) {
      if(!isNaN(v))
        _value = v;
    }
  });
}

MyNumber.prototype = (function() {
  var proto = {};
  proto.add = function(o2) {
    if (o2 instanceof MyNumber) {
      this.value = this.value + o2.value;
    } else {
      throw new Error('Mismatched type. Expected an object of type MyNumber but got ' + o2.constructor.name);
    }
  }
  return proto;
})();

var o1 = new MyNumber(10);
var o2 = new MyNumber(20);

o1.add(o2);
console.log(o1.value);

var o3 = {
  value: 40
}

try {
  o1.add(o3);
} catch (ex) {
  console.log(ex.message)
}

Upvotes: 1

Related Questions