我每次运行吐司功能时都试图为我的烤面包机对象添加一个新的值对,但它似乎没有工作,我不知道为什么。 这是代码:
var Toaster = function(){
function cook(type,temp){
var food = type;
var amtCooked;
if(temp >7){
amtCooked = "Well Done!"
}
else if(temp > 4){
amtCooked = "Medium";
}
else{
amtCooked = "Lightly done!";
}
this[food] = food + amtCooked;
}
return{
toast: function(typeOfBread,setting){
cook(typeOfBread,setting)
}
};
}
我希望能够调用像
这样的函数var v = Toaster();
v.toast("bread",4)
并且v
应该有{bread:"medium"}
但是this[food]
部分似乎没有起作用。
答案 0 :(得分:1)
你可以这样做:
var Toaster = function() {
this.cooked = {};
}
Toaster.prototype.cook = function(type, temp) {
var food = type;
var amtCooked;
if (temp > 7) {
amtCooked = "Well Done!"
} else if (temp > 4) {
amtCooked = "Medium";
} else {
amtCooked = "Lightly done!";
}
this.cooked[food] = amtCooked;
}
Toaster.prototype.toast = function(typeOfBread, setting) {
this.cook(typeOfBread, setting);
};
Toaster.prototype.history = function() {
var record = '';
Object.keys(this.cooked).forEach(function(typeOfBread) {
record += typeOfBread + ': ' + this.cooked[typeOfBread] + '\n';
}.bind(this));
alert(record);
};
var t = new Toaster();
t.toast('Rye', 3);
t.toast('White', 3);
t.toast('Wheat', 10);
t.history();
然后提醒:
Rye: Lightly done!
White: Lightly done!
Wheat: Well Done!
JSFiddle:http://jsfiddle.net/ypbybL9g/
答案 1 :(得分:1)
您似乎混合了Factory和Constructor, 如果要创建Toaster构造函数,请更改为:
var Toaster = function(){
function cook(type,temp){
var food = type;
var amtCooked;
if(temp >7){
amtCooked = "Well Done!"
}else if(temp > 4){
amtCooked = "Medium";
}else{
amtCooked = "Lightly done!";
}
this[food] =food + amtCooked;
}
this.toast =function(typeOfBread,setting){
cook.call(this, typeOfBread,setting);
};
}
//Usage
var v = new Toaster();
v.toast("bread",4)
cook
使上下文不明确,使用cook.call(this)
给它context
,所以this[food]
这将是请参考创建的toast对象。或者,如果你想要一个ToasterFactory
,那么Code会喜欢这个:
var Toaster = function(){
function cook(type,temp){
var food = type;
var amtCooked;
if(temp >7){
amtCooked = "Well Done!"
}
else if(temp > 4){
amtCooked = "Medium";
}
else{
amtCooked = "Lightly done!";
}
this[food] = food + amtCooked;
}
return {
toast: function(typeOfBread,setting){
cook.call(this, typeOfBread,setting);
}
};
}
//Usage
var v = Toaster();
v.toast("bread",4)
为它创建了jsFiddle。根据您想要调用Toaster的方式,可能Factory
就是您想要的。
答案 2 :(得分:1)
这是你要找的东西吗?
var Toaster = function(){
function cook(type,temp){
var food = type;
var amtCooked;
if(temp >7){
amtCooked = "Well Done!"
}else if(temp > 4){
amtCooked = "Medium";
}else{
amtCooked = "Lightly done!";
}
return {food : amtCooked};
}
return{
toast: function(typeOfBread,setting){
return cook(typeOfBread,setting)
}
};
}
var x = Toaster().toast("a", "b")
$(function(){
console.log(JSON.stringify(x));
});
输出生成= {"食物":"轻轻地完成!"}