Javascript jQuery代码设计问题

时间:2013-09-17 11:14:36

标签: javascript jquery javascript-objects code-design javascript-namespaces

我正在尝试创建一些骨架来帮助我轻松开发我的代码。 在阅读了一些解决方案后,我创造了更适合我需求的东西:

    (function ($, a) {
       var User = {
            init: function (first_name, last_name) {
                this.firstName = first_name;
                this.lastName = last_name;
            },

            cacheElements: function () {
                this.$profileHeader = $('.profile-header');
                console.log(this.$profileHeader);
            },

            bindEvents: function () {
               this.$profileHeader.find("#set-new-name").on("click", this.setNewName);
            },

            setNewName: function () { 
                console.log(this.$editProfilePopups); //undefined
                console.log(User.$editProfilePopups); //work
                //...
            },  
        };

        a.User = User;
    })(jQuery, MyApp);

jQuery(document).ready(function (a) {
    MyApp.User.init();
});

你能解释一下'这个'是怎么回事吗? 在从init()调用的函数中,我看到'this',但是从事件调用的函数我看不到这个。如何在setnewName函数中使用我的cacheElements?

1 个答案:

答案 0 :(得分:0)

您可以使用javascript类机制始终将“this”范围锁定为您想要的内容 您可以找到工作代码here

function log(msg) {
   $('#console').append($('<p/>').html(msg));
}
var MyApp = {};
(function ($, a) {
   a.User = new function () {
       this.firstName = 'default first name';
       this.lastName = 'default last name';
       this.init = function (firstName, lastName) {
           this.firstName = firstName;
           this.lastName = lastName;
       };
       this.setNewName = function (firstName, lastName) {
           log('before first name is: ' + this.firstName); //work
           this.firstName = firstName;
           log('now the first name is: ' + this.firstName);
           //log(User.$editProfilePopups); //wont work
           //...
        };
      };
})(jQuery, MyApp);

jQuery(document).ready(function () {
   MyApp.User.init('Peter', 'T');
   $('#btn').click(function () {
       MyApp.User.setNewName('NewName1', 'NewName2');
   });
});