나는 현재 요리 레시피를 표시하기 위해 OOP를 사용하고 있습니다. 내가 document.write
방법을 사용할 때를 제외하고는 모든 것이 좋습니다 . 을 표시 할 때 텍스트는 "$ 2.00undefined"및 "$ 6.00undefined"로 표시 price
됩니다. 내 코드는 다음과 같습니다.
<html>
<body>
<p id = "p"></p>
<script>
function Recipe(name, ingredients, price) {
this.name = name;
this.ingredients = ingredients;
this.price = price;
}
function describe(name, ingredients, price) {
document.write("<h2> Recipe name: " + name + "</h2> Ingredients: " + ingredients + "<br />Price: " + price);
}
var instantRamen = new Recipe("Ramen", "Ramen noodles, hot water, salt, (optional) green pepper", "$2.00");
var Bagel = new Recipe("Ham and cheese bagel", "Bagel (preferably an everything bagel), ham, cheese (of any type), pepper (just a little)", "$6.00");
document.write(describe(instantRamen.name, instantRamen.ingredients, instantRamen.price));
document.write(describe(Bagel.name, Bagel.ingredients, Bagel.price));
</script>
</body>
</html>
예상되는 결과는 "레시피 이름 :라면 (줄 바꿈) 재료 :라면, 뜨거운 물, 소금, (선택 사항) 피망 (줄 바꿈) 가격 : $ 2.00"과 같지만 가격은 "$ 2.00 undefined"가됩니다. 다른 모든 것이 작동합니다.
원래 instantRamen
및 Bagel
인스턴스를 만들 때 문제가 있다고 생각했기 때문에 일부 구문을 아무 소용없이 변경해 보았습니다.
당신은 이렇게 할 수 있습니다 return
.
값을 반환하지 않기 때문입니다. Thatsyundefined
function Recipe(name, ingredients, price) {
this.name = name;
this.ingredients = ingredients;
this.price = price;
}
function describe(name, ingredients, price) {
return "<h2> Recipe name: " + name + "</h2> Ingredients: " + ingredients + "<br />Price: " + price;
}
var instantRamen = new Recipe("Ramen", "Ramen noodles, hot water, salt, (optional) green pepper", "$2.00");
var Bagel = new Recipe("Ham and cheese bagel", "Bagel (preferably an everything bagel), ham, cheese (of any type), pepper (just a little)", "$6.00");
document.write(describe(instantRamen.name, instantRamen.ingredients, instantRamen.price));
document.write(describe(Bagel.name, Bagel.ingredients, Bagel.price));
<html>
<body>
<p id = "p"></p>
</body>
</html>
나는 제거한 document.write
와 return
문자열.
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다