如何从构造函数中的函数返回对象属性?

史努比学校

我正在用 JavaScript 构建一个小型世界构建器(大型模拟的一部分)。

我试图通过为它分配一个函数输出来在构造函数中定义一个对象的属性。

在下面的代码中,“this.identifier”的执行就像一个魅力,但我想为例如“this.gender”分配更复杂的函数。

“this.gender”中,我想使用 math.random.math.floor 来循环遍历一个数组(有两个值,男性和女性)。

当我编写实际函数时,'this.gender'从新的 Human 对象中删除。

 {
   "identifier":42,
   "lifestate":"Alive",
   "health":"100",
   "age":"10",
   "metabolism":"12",
   "econsumption":"11111",
   "parent":"yes"
}
  • 在我将其更改为函数的那一刻,性别就被删除了。

我试过使用 return 语句,但没有区别。

class Bluehuman {
  constructor() {
    this.identifier = Math.floor((Math.random() * 100));
    this.lifestate = 'Alive';
    this.health = '100';
    this.age = '10';
    this.metabolism = ['Low','Medium','High'];
    this.econsumption = '11111';
    this.parent = ['Yes','No'];
    this.gender = ['Male','Female']; // Want to change this to a function without dropping from the new Bleuhuman object
    }
  }

var bluehuman = {};
var bluehumans = [];

for (var i = 0; i < 10; i++) {
  bluehuman[i] = new Bluehuman();
  bluehumans.push(bluehuman[i]);
}

var arrayPrint = JSON.stringify(bluehumans);
console.log(arrayPrint)

如何将函数的输出分配给 'this.gender' 而不会从新的 bluehuman 对象中删除它?

丹亚尔·伊姆兰

你不需要一个函数,一个表达式就可以解决你的问题

class Bluehuman {
  constructor() {
    this.identifier = Math.floor((Math.random() * 100));
    this.lifestate = 'Alive';
    this.health = '100';
    this.age = '10';
    this.metabolism = ['Low','Medium','High'];
    this.econsumption = '11111';
    this.parent = ['Yes','No'];
    this.gender = ['Male','Female'][Math.round(Math.random())];
    }
  }

var bluehuman = {};
var bluehumans = [];

for (var i = 0; i < 10; i++) {
  bluehuman[i] = new Bluehuman();
  bluehumans.push(bluehuman[i]);
}

var arrayPrint = JSON.stringify(bluehumans);
console.log(arrayPrint)

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

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

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

JavaScript对象构造函数返回属性

如何在对象构造期间在函数中设置属性?

从构造函数返回对象

函数的原型属性如何影响对象的构造函数属性?

如何从返回对象的函数中获取属性的值?

返回对象属性的函数

尝试在构造函数中设置类属性时,用户对象返回空

如何访问在构造函数中创建的对象?

如何在javascript中查看函数的构造函数属性?

如何绑定由AngularJS中的函数构造函数创建的对象

如何在构造函数中构造对象并分配引用?

如何返回没有副本构造函数的对象

如何在javascript对象中使用构造函数以仅使用`this`中的属性?

子构造函数中的Java父对象的private属性

JavaScript中的对象属性名称与构造函数参数

为什么要在构造函数中声明对象属性

如果未重写构造函数属性,为什么对象的构造函数属性指向扩展函数中的父函数的构造函数而不是F

如何访问构造函数的属性?

如何从函数返回&&对象?

如何从函数返回对象?

如何从函数返回对象?

构造函数中的覆盖属性

在构造函数中传递对象

如何使函数返回VBA中的对象列表

如何返回在函数中创建的对象?

如何从 PHP 中的函数返回哈希对象?

对象构造函数作为Javascript中的函数

如何键入一个函数,该函数返回对象中存在于属性中的数组中的单个元素

如何使用属性从构造函数中Kotin的实例方法中的?