Javascript - 帮助原型和属性?

Javascript - Help w/ prototypes and properties?

我目前正在为我的 javascript class 编写代码,但我遇到了死胡同。任务是制作一个具有以下几个属性的 "virtual pet app":饥饿、生病和孤独。还有两个共享主要宠物对象的原型(狗和鱼)。到目前为止,这是我的代码:

'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 很好,而是打印任何空字符串吗?提前致谢!

您的意图似乎是在 none 的属性为真时显示 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;
};