是否可以将一个属性值作为参数传递给通过函数计算其值的另一个属性?(在带有类的Javascript ES6中)

DevCoder

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);

问题:在方法d()语句“ let x”中,可以将x1属性用作x2:this.e()调用的参数,如下所示:

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

尝试了几种组合都没有用。基本上,有比我明确希望作为参数x1重复输入“ this.b()”作为this.e()参数更好的方法吗?

约瑟夫·波德莱基(JózefPodlecki)

您可以使用IIFE或推荐的@Adeel

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);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

Related 相关文章

热门标签

归档