Can one property value be passed as a argument to another property whose value is computed via a function ? (in Javascript ES6 with classes)

Viewed 27

class A {
    constructor(inval){
    this.c = inval;
    }

b() {
return this.c + 1;
}

e(z) {
    return z+ Math.floor(Math.random()*10);
}

d() {
    let x = {
        x1: this.b(),
        x2: this.e(this.b()),
    }
    return x;
}
}

var inst = new A(5);
var instret = inst.d();
console.log(instret);

Question: in method d() statement "let x" is it possible to use the x1 property as a argument to x2:this.e() call like this:

let x = {
        x1: this.b(),
        x2: this.e(x1),
    }

tried several combinations none worked. Basically is there a better way than to repeatedly type "this.b()" as parameter to this.e() when what I clearly want as parameter is x1 ?

2 Answers

Set key2 as a function and use this to access another key from the same object.

var obj = {
  key1: 5,
  key2: function() {
    return this.key1 + 10;
  }
};

alert(obj.key2()); // 15

You can use IIFE or what @Adeel recommended

class A {
  constructor(inval) {
    this.c = inval;
  }

  b() {
    return this.c + 1;
  }

  e(z) {
    return z + Math.floor(Math.random() * 10);
  }

  d() {
    let x = ((x1) => ({
      x1,
      x2: this.e(x1),
    }))(this.b());
    
    return x;
  }
}

var inst = new A(5);
var instret = inst.d();
console.log(instret);

Related