Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you put an if/else statement inside an object key?

Tags:

javascript

I'm trying to create a Person class. The person's age would be a random number, determined by an if/else statement. Right now it seems to only work if I place the function outside of the object, or as a separate key.

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

Is there a way for me to put the function directly into the "this.age" key and have the same thing happen, like so:

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);
        }
};
like image 954
Korey Avatar asked Mar 27 '26 20:03

Korey


1 Answers

You can execute the function immediately:

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);
        }
    })();
};
like image 197
Intelekshual Avatar answered Apr 02 '26 20:04

Intelekshual