Javascript:如何通过方法调用定义对象的属性?

时间:2013-12-02 04:01:03

标签: javascript function object undefined

我正在尝试在创建对象时通过一系列函数调用来设置对象(Robolord)的'moniker'属性。这是我的代码:

function RobolordCreator (moniker) {
    this.moniker = moniker;
};

RobolordCreator.prototype.Attack = function (color) {
    console.log(this.moniker + " fires a " + color + " laser for " + 2 + " damage!");
};

var Robolord = new RobolordCreator(MonikerGenerator());

function MonikerGenerator () {

    function Chancey (percent) {
        function rando (percent) {
            percent = "." + percent;
            return ((Math.random() <= percent) ? true : false);
        };

        if(rando(percent) == true){
            RandomVowel();
        } else {
            RandomConsonant();
        };
    };
    Chancey(50);
};

function RandomConsonant () {
    var consonant = ["q", "w", "r", "t", "p", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"];
    return consonant[(Math.floor(20 * Math.random()))];
};

function RandomVowel () {
    var vowel = ["a", "e", "i", "o", "u", "y"];
    return vowel[(Math.floor(6 * Math.random()))];
};

Robolord.Attack("green");

现在,它正在打印出“未定义的激发绿色激光造成2点伤害!”我怎样才能使RandomConsonant和RandomVowel函数在调用我的对象Robolord的'moniker'属性时传递结果?

2 个答案:

答案 0 :(得分:1)

遗失了一对return

function MonikerGenerator () {

    function Chancey (percent) {
        function rando (percent) {
            percent = "." + percent;
            return ((Math.random() <= percent) ? true : false);
        };

        if(rando(percent) == true){
            return RandomVowel(); //return Chancey result
        } else {
            return RandomConsonant(); //return Chancey result
        };
    };
    return Chancey(50); //return Moniker to caller
}

Demo

答案 1 :(得分:0)

如果您要查找多个字符长的名称,则必须存储名称并为其添加字符。这是执行该操作的代码版本。

function Robolord(moniker) {
    this.moniker = moniker
}

Robolord.prototype.attack = function (color) {
    console.log(this.moniker + " fires a " + color + " laser for " + 2 + " damage!")
};

var robolord = new Robolord(generateName(8, 50))

function generateName(length, percent) {
    var name = ''

    for (var i = 0; i < length; i++) {
        if (randomInt(1,100) > percent) {
            name += randomVowel()
        } else {
            name += randomConsonant()
        }
    }

    return name
}

function randomConsonant () {
    var consonant = ["q", "w", "r", "t", "p", "s", "d", "f", "g", "h", "j", "k", "l", "z", "x", "c", "v", "b", "n", "m"]
    return consonant[(Math.floor(20 * Math.random()))]
}

function randomVowel () {
    var vowel = ["a", "e", "i", "o", "u", "y"]
    return vowel[(Math.floor(6 * Math.random()))]
}

function randomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min
}

robolord.attack("green");

我为重命名一些事情道歉,我正在玩它:)

函数generateName现在需要一个长度和元音的百分比(我假设是原始意图)。例如,这会生成8个字母长和50%元音的名称。

我添加了一个名为randomInt的函数,它给出了一个范围内的随机数 - 我使用一个大致相同的函数来生成游戏中的名字/地形/ NPC。

http://jsfiddle.net/ayvaV/