Javascript - 帮助w /原型和属性?

时间:2015-04-28 00:25:57

标签: javascript properties prototype

我目前正在为我的javascript课程编写代码而且我已经走到了尽头。任务是制作一个虚拟宠物应用程序"有几个属性:饥饿,生病和孤独。还有两个原型(狗和鱼)共享主要宠物对象。到目前为止,这是我的代码:

'use strict';

// Pet Prototype
var pet = {
    name: 'Your Pet',
    hungry: true,
    ill: false
};


pet.feed = function(){
    this.hungry = false;
    return this.name + ' is full.';
};


pet.newDay = function(){
    for (var prop in this){
        if (typeof this[prop] === 'boolean'){
            this[prop] = true;
        }
    }
    return 'Good morning!';
};


pet.check = function(){
    var checkVal = '';

    for (var prop in this){
        if (typeof this[prop] === 'boolean'
            && this[prop] === true){
            checkVal += this.name + ' is ' + prop + '. ';
        } 
    }
    if (typeof this[prop] === 'boolean'
            && this[prop] === false){
            checkVal = this.name + ' is fine.';
    }
    return checkVal;
};

// Fish Prototype
var fish = Object.create(pet);


fish.clean = function(){
    this.ill = false;
    return this.name + ' likes the clean tank.';
};


// Dog Prototype
var dog = Object.create(pet);


// Lonely Property
dog.lonely = false;


dog.walk = function(){
    this.ill = false;
    return this.name + ' enjoyed the walk!';
}


dog.play = function(){
    this.lonely = false;
    return this.name + ' loves you.';
}

代码还有更多,但我认为你们现在已经得到了主旨。问题是我的检查功能无法正常工作......

console.log(myDog.check());      // Fido is hungry.
console.log(myDog.feed());       // Fido is full.
console.log(myDog.check());      // Fido is fine.
console.log(myFish.check());     // Wanda is hungry.
console.log(myFish.feed());      // Wanda is full.
console.log(myFish.check());     // Wanda is fine.
console.log(myDog.newDay());     // Good morning!
console.log(myFish.newDay());    // Good morning!
console.log(myDog.check());      // Fido is hungry. Fido is lonely. Fido is ill.

这是我的输出应该是什么,但这是我的输出:

Fido is hungry. 
Fido is full.
(an empty string)
Wanda is hungry. 
Wanda is full.
(an empty string)
Good morning!
Good morning!
Fido is hungry. Fido is lonely. Fido is ill. 

有人可以指导我为什么我的检查功能不打印pet.name很好,而是打印任何空字符串?提前谢谢!

1 个答案:

答案 0 :(得分:3)

如果没有任何属性为真,您的意图就是显示is fine。而不是检查this[prop],因为循环后prop的值不可预测而没有意义,只需检查循环是否设置了checkVal

pet.check = function(){
    var checkVal = '';

    for (var prop in this){
        if (typeof this[prop] === 'boolean'
            && this[prop] === true){
            checkVal += this.name + ' is ' + prop + '. ';
        } 
    }
    if (checkVal == ''){
        checkVal = this.name + ' is fine.';
    }
    return checkVal;
};