我正在尝试创建一个 Person 类。该人的年龄将是一个随机数,由 if/else 语句确定。现在它似乎只有在我将函数放在对象之外或作为单独的键时才有效。
function age(x) {
if (x.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) {
return Math.floor(Math.random()*40+1);
}
else {
return Math.floor(Math.random()*40+41);
}
}
function person(name) {
this.name = name;
this.age = age(name);
}
var people = {
joe: new person("Joe")
};
console.log(people.joe.age);
\\ returns a number 41-80
有没有办法让我将函数直接放入“this.age”键并发生同样的事情,如下所示:
function person(name) {
this.name = name;
this.age = function age() {
if (this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) {
return Math.floor(Math.random()*40+1);
}
else {
return Math.floor(Math.random()*40+41);
}
};