-1

関数feedAmountをコンソールに出力しようとしていますが、行き詰まります。誰かが私をまっすぐにするのを手伝ってくれる(そして必要ならこれを最適化する)ことができますか?追加の質問として、プロトタイプを作成できますか?Chicken.prototype.chickenFeed( "small")?ありがとう!

var chicken = new chickenObj("cluck");
chicken.talk();

function chickenObj(says) {

    this.says = says;

    this.talk = function talk() {
        console.log("::" + this.says);
    }
}

chicken.chickenFeed = new chickenFeed("small");
chicken.chickenFeed.foodAmount();

function chickenFeed(size) {

    this.size = size;

    function foodAmount() {

        if(this.size === "small") {
            this.food = "1 pound of feed";
        } else if(this.size === "medium") {
            this.food = "2 pound of feed";
        } else if(this.size === "large") {
            this.food = "3 pound of feed";
        }

        console.log(this.food);
    }
}
4

2 に答える 2

2

foodAmountを使用可能にする場合は、コンストラクターによって作成されるオブジェクト(this.foodAmountを使用)または関数プロトタイプ(chickenFeed.prototype.foodAmount)で定義する必要があります。

function chickenFeed(size) { 
    this.size = size;

    this.foodAmount = function() { 
        if (this.size === "small") { 
            this.food = "1 pound of feed";
        } else if (this.size === "medium") { 
            this.food = "2 pound of feed";
        } else if (this.size === "large") { 
            this.food = "3 pound of feed";
        }

        console.log(this.food);
    }
}

または:

function chickenFeed(size) { 
    this.size = size;
}

chickenFeed.prototype.foodAmount = function() {
    if (this.size === "small") { 
        this.food = "1 pound of feed";
    } else if (this.size === "medium") { 
        this.food = "2 pound of feed";
    } else if (this.size === "large") { 
        this.food = "3 pound of feed";
    }

    console.log(this.food);
}
于 2012-06-21T11:45:45.583 に答える
1
function chickenFeed(size) { 
    this.size = size;
}

chickenFeed.prototype.foodAmount = function () { 

    if (this.size === "small") { 
        this.food = "1 pound of feed";
    }
    else if (this.size === "medium") { 
        this.food = "2 pound of feed";
    }
    else if (this.size === "large") { 
        this.food = "3 pound of feed";
    }

    console.log(this.food);
};

そして、あなたがそれにいる間、同様に入れ.talkてください。chickenObj.prototype

于 2012-06-21T11:49:48.580 に答える