javascript - 我正在尝试使用原型(prototype)方法打印类的属性,但它不起作用

标签 javascript

我正在学习 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/

相关文章:

javascript - 鼠标悬停时的 SVG 工具提示?

javascript - index.html 中始终禁用按钮标记

javascript - Angular2 中对象的 $$hashKey?

javascript - 更改时的 jQuery 单选按钮不起作用

javascript - 使用 Chrome 扩展的 Javascript 检查另一个网站上的所有框时出现问题

带有 for 的 Javascript 表

javascript - 有条件的 ng-click

javascript - 检测应用程序重新聚焦事件

javascript - 为什么以下代码没有更改 Node.js 中我的对象中的属性

javascript - Rails 应用程序 JavaScript 放置在 application.js 中时不起作用