【问题标题】:How do I return an object property from a function within a constructor?如何从构造函数中的函数返回对象属性?
【发布时间】:2019-05-02 15:32:50
【问题描述】:

我正在用 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"
}
  • gender 在我将其更改为函数时被删除。

我尝试过使用 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 对象中删除?

【问题讨论】:

  • 这应该不是问题。您应该显示不起作用的代码。
  • JSON 不能包含函数。
  • @JonasWilms,听起来 OP 想要一个函数的 result,比如 this.identifier: How can I assign the output of a function...
  • 能否请您添加不起作用的代码(与功能)?
  • 感谢所有 cmets Jonas 和 Mark。真的很感激。下面@DanyalImran 的评论解决了我的问题:-)

标签: javascript arrays object constructor


【解决方案1】:

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

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)

【讨论】:

  • 谢谢丹亚尔。你的解决方案奏效了。我会用 this.motabolism 和其他的来试试。真的很感激:-)
  • 没问题,很高兴能帮上忙。如果此解决方案有效,请将其标记为已验证,以便将来可能会遇到此问题的人知道如何解决它:) @SnoobySchool
【解决方案2】:

您可以将函数分配为任何其他值

  this.test = function() { };

然后您就可以将其称为:

  new Bluehuman().test();

如果你直接将它记录到控制台,你也会看到它:

  console.log(new Bluehuman());

如果你在上面调用JSON.stringify,它会变成一个只包含数据的字符串,函数(和很多其他的东西)会被删除。

【讨论】:

  • 谢谢乔纳斯。我将在更新部分使用您的建议。
猜你喜欢
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多