Javascript 如何将if/else语句放入对象键中?

Javascript 如何将if/else语句放入对象键中?,javascript,Javascript,我正在尝试创建一个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(Ma

我正在尝试创建一个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
功能年龄(x){

如果(x.toLowerCase().charCodeAt(0)您可以立即执行该函数:

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);
        }
    })();
};
职能人员(姓名){
this.name=名称;
this.age=(函数age(){

如果(this.name.toLowerCase().charCodeAt(0)您可以立即执行该函数:

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);
        }
    })();
};
职能人员(姓名){
this.name=名称;
this.age=(函数age(){

如果(this.name.toLowerCase().charCodeAt(0),则必须定义闭包(函数)并立即执行它

  function person(name) {
        this.name = name;
        this.age = (function age() {
            var x = this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) ? 1 : 41;
                return Math.floor(Math.random()*40+x);
            })();
    };
职能人员(姓名){
this.name=名称;
this.age=(函数age(){

var x=this.name.toLowerCase().charCodeAt(0)您必须定义闭包(函数)并立即执行它

  function person(name) {
        this.name = name;
        this.age = (function age() {
            var x = this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) ? 1 : 41;
                return Math.floor(Math.random()*40+x);
            })();
    };
职能人员(姓名){
this.name=名称;
this.age=(函数age(){

var x=this.name.toLowerCase().charCodeAt(0)谢谢,通过将函数转换为语句并立即执行它,学到了一些新东西。谢谢,通过将函数转换为语句并立即执行它,学到了一些新东西。
  function person(name) {
        this.name = name;
        this.age = (function age() {
            var x = this.name.toLowerCase().charCodeAt(0) <= "g".charCodeAt(0)) ? 1 : 41;
                return Math.floor(Math.random()*40+x);
            })();
    };