2016-10-11 5 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を使用することができます

関連する問題