Reading a function from another function

The problem is that when clicked, .testit does not execute the function do_alert();and gives me an error:

do_alert (); undefined.

What is the problem? the main function is helpersalready read when the page loads, why can it "get this function from the function logout_users?

var setup_system = (function($) {
  "use strict";

  return {
    init: function() {
      this.logout_users();
      this.helpers();
    },
    logout_users: function() {
      $(document).on('click', '.test', function(e) {
        e.preventDefault();
        do_alert();
      });
    },
    helpers: function() {
      function do_alert() {
        alert();
      }
    }
  };
})(jQuery);

jQuery(document).ready(function() {
  setup_system.init();
});

NOTE. I am trying to re-read the function of helpers by adding this.helpers()in logout_users, but nothing has changed.

+4
source share
3 answers

This is because you defined do_alert()within the function helpers.

, . ( , , "" ), helpers, , , . :

var setup_system = (function($) {
  "use strict";

  return {
    init: function() {
      this.logout_users();
    },
    logout_users: function() {
      var _obj = this;
      $(document).on('click', '.test', function(e) {
        e.preventDefault();
        _obj.helpers.do_alert();
      });
    },
    helpers: {
      do_alert: function() {
        alert('foo');
      }
    }
  };
})(jQuery);

jQuery(function() {
  setup_system.init();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="test">Click me</div>
Hide result

, _obj click, this clicked .test.

+3

Do_alert helpers, .

logout_user , :

 var setup_system = (function ($) {
 "use strict";

 return {

     init: function () {
        this.logout_users();
        this.helpers();
     },

    logout_users: function() {

            function do_alert(){
            alert();
        }

        $(document).on('click', '.test', function(e){
            e.preventDefault();
            do_alert();
        });
    },

    helpers: function () {

        function do_alert(){
            alert();
        }
       }

   };
})(jQuery);

jQuery(document).ready(function () {
    setup_system.init();
});
+1

helpers init, , , do_alert. . do_alert - , helpers. do_alert helpers.

, . , , : helpers , do_alert, :

   helpers: function() {
    this.doAlert = function() {
        alert();
    }
}

doAlert() , jQuery, . , doAlert . :

 logout_users: function() {
    var self = this;
  $(document).on('click', '.test', function(e) {
    e.preventDefault();
    self.doAlert();
  });
0
source

Source: https://habr.com/ru/post/1693539/


All Articles