-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 回答