2016-10-11 55 views
1

我正在学习JavaScript,这是我试图做的,我采取了食谱,然后通过使用原型,我添加了一个方法被我定义的所有类/对象继承。我试图用原型方法打印类的属性,但它不工作

但它不工作...:C

以下是我有:

function Recipe(name, origin, auther, ingredients, directions) { 
    this.name = name; 
    this.origin = origin; 
    this.author = auther; 
    this.ingredients = ingredients; 
    this.directions = directions; 
}; 

Recipe.prototype.printRecipe(){ 
    return "<ul>" + "<li>" + this.name + "</li>" + "<li>" + this.origin + "</li>" + "<li>" + this.author + "</li>" + "<li>" + this.ingredients + "</li>" + "<li>" + this.directions + "</li>" +"</ul>"; 
} 

var Salad = new Recipe("Fruit Salad", "Unknown", "Unknown", "Apples, Bananas, Berries, Milk, Sugar, Dry fruits", "<ul><li>sdasds</li></ul>") 

document.getElementById("text").innerHTML = Salad.printRecipe(); 

编辑:固定,所有的代码将被格式化为代码块

回答

0

这是语法添加属性:

SomeClass.prototype.propertyName = "property";

这是语法添加方法:

SomeClass.prototype.methodName = function() { return this.property; };

所以,你应该写你这样的代码:

Recipe.prototype.printRecipe = function(){ 
    return "<ul>" + "<li>" + this.name + "</li>" + "<li>" + this.origin + "</li>" + "<li>" + this.author + "</li>" + "<li>" + this.ingredients + "</li>" + "<li>" + this.directions + "</li>" +"</ul>"; 
}; 
+0

OHHHH非常感谢! :d – buoyantair

1

你所要做的是一个方法添加到您的prototype,所以你应该做的:

function Recipe(name, origin, auther, ingredients, directions) { 
    this.name = name; 
    this.origin = origin; 
    this.author = auther; 
    this.ingredients = ingredients; 
    this.directions = directions; 
}; 

// Note how we changed the syntax of this line slightly and added the 'function' word 
Recipe.prototype.printRecipe = function(){ 
    return "<ul>" + "<li>" + this.name + "</li>" + "<li>" + this.origin + "</li>" + "<li>" + this.author + "</li>" + "<li>" + this.ingredients + "</li>" + "<li>" + this.directions + "</li>" +"</ul>"; 
} 

var Salad = new Recipe("Fruit Salad", "Unknown", "Unknown", "Apples, Bananas, Berries, Milk, Sugar, Dry fruits", "<ul><li>sdasds</li></ul>") 

document.getElementById("text").innerHTML = Salad.printRecipe(); 

可以使用W3Schools Javascript course更多地了解原型和看到的例子

相关问题