1

我正在尝试创建一个 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);
        }
};
4

3 回答 3

5

您可以立即执行该功能:

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);
        }
    })();
};
于 2013-02-28T23:10:18.677 回答
4
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);
        })();
};

(function(){})()正在执行它。

(function(){}) //this converts the function into a statement
() // this executes
于 2013-02-28T23:09:52.093 回答
2

您必须定义闭包(函数)并立即执行它。

  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);
            })();
    };
于 2013-02-28T23:11:25.353 回答