我正在尝试使用闭包来实现以下javascript代码,并且得到这样的输出。此处,整个功能都在浏览器中显示
`function apple(){ var test1 = '
'+ '
'+ ' This is apple'+ '
'+ '
'; return test1; }`
所需的输出:
我只希望打印“这是苹果”,而不是整个功能。请检查下面的代码。任何帮助表示赞赏。
javascript代码
`function init(){
function fruits(){
function apple(){
var test1 = '<div id="main">'+
' <div>'+
' This is apple'+
' </div>'+
'</div>';
return test1;
}
function mango(){
var test2 = '<div id="main">'+
' <div>'+
' This is mango'+
' </div>'+
'</div>';
return test2;
}
return{
apple: apple,
mango: mango
}
}
function print(var1){
document.write(var1)
}
return {
fruits:fruits,
print: print
}
}`
HTML代码:调用javascript代码
`<html>
<head>
<script src="script.js"></script>
</head>
<body>
<script>
//creating object for the main function which is init
var object = init();
//creating object for the function fruits
var fruits = object.fruits();
//passing function apple inside fruits to print function.
//function apple returns html div.
//function print prints the html using document.write
object.print(fruits.apple);
</script>
</body>
</html> `
答案 0 :(得分:0)
您需要在某个地方调用fruits.apple
,因为它是一个函数。
我建议将通话移至print
function init() {
function fruits() {
function apple() {
return '<div id="main"><div>This is apple</div></div>';
}
function mango() {
return '<div id="main"><div>This is mango</div></div>';
}
return { apple, mango };
}
function print(fruit) {
document.write(fruit());
}
return { fruits, print };
}
var object = init(),
fruits = object.fruits();
object.print(fruits.apple);