2016-10-11 57 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更多地瞭解原型和看到的例子

相關問題