我正在学习 javascript,这就是我尝试做的,我采取了一个配方,然后通过使用原型(prototype),我添加了一个由我定义的所有类/对象继承的方法。
但是它不起作用...: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();
编辑:已修复,所有代码都将格式化为代码块
最佳答案
您想要做的是向您的原型(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了解有关原型(prototype)的更多信息并查看示例
关于javascript - 我正在尝试使用原型(prototype)方法打印类的属性,但它不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39974901/