简体   繁体   English

下面的关闭示例未正确返回

[英]The below closure example not returning properly

I am trying to implement the below javascript code using closures and I get the output like this. 我试图使用闭包实现下面的javascript代码,我得到这样的输出。 Here the whole function is printed in the browser 此处,整个功能都在浏览器中打印

`function apple(){ var test1 = '
'+ '
'+ ' This is apple'+ '
'+ '
'; return test1; }`

Desired output: 所需的输出:

I only want "This is apple" to be printed and not the whole function. 我只希望打印“这是苹果”,而不是整个功能。 Please check the code below. 请检查下面的代码。 Any help greatly appreciated. 任何帮助,不胜感激。

javascript code 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 code : which calls the javascript code 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> `

You need to call fruits.apple somewhere, because it is a function. 您需要在某个地方调用fruits.apple ,因为它是一个函数。

I suggest to move the call inside of print 我建议将通话移至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); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM