[英]How do I return an object property from a function within a constructor?
I'm building a small world builder in JavaScript (part of a larger simulation). 我正在用JavaScript构建一个小的世界构建器(较大模拟的一部分)。
I'm trying to define an object's property in the constructor function by assigning a functions output to it. 我试图通过向其分配函数输出来在构造函数中定义对象的属性。
In the code below, 'this.identifier' executes like a charm, but I want to assign more complex functions to for instance 'this.gender'. 在下面的代码中, “ this.identifier”的执行就像一个超级按钮 ,但是我想为“ this.gender”分配更复杂的功能。
In 'this.gender' I want to use math.random.math.floor to cycle through an array (that has two values, male and female). 在“ this.gender”中,我想使用math.random.math.floor循环遍历一个数组(该数组具有两个值,即male和female)。
When I write the actual function, 'this.gender' is dropped from the new Human object. 当我编写实际函数时,将从新的Human对象中删除“ this.gender” 。
{
"identifier":42,
"lifestate":"Alive",
"health":"100",
"age":"10",
"metabolism":"12",
"econsumption":"11111",
"parent":"yes"
}
I've tried using a return statement, but it makes no difference. 我试过使用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)
How can I assign the output of a function to 'this.gender' without having it dropped from the new bluehuman object? 我如何将函数的输出分配给'this.gender'而不将其从新的bluehuman对象中删除?
You don't need a function, an expression is just fine to solve your problem 您不需要功能,表达式就可以解决您的问题
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)
You can just assign a function as any other value 您可以将一个函数分配为任何其他值
this.test = function() { };
you will then be able to call it as: 然后,您可以将其称为:
new Bluehuman().test();
and if you log it to the console directly, you'll also see it: 如果直接将其登录到控制台,您还将看到它:
console.log(new Bluehuman());
If you however call JSON.stringify
on it, it will be turned into a string containing only data, functions (and a lot of other things) get removed. 但是,如果您在其上调用
JSON.stringify
,它将变成仅包含数据,函数(以及许多其他内容)的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.