【问题标题】:Encapsulate javascript code in a global object for clearer code将 javascript 代码封装在全局对象中以获得更清晰的代码
【发布时间】:2011-03-06 11:23:34
【问题描述】:

我正在尝试使用 jQuery 和 jQueryUI 的 datepicker 内联模式让事情正常工作。

我想将我的所有代码放在一个全局对象中,并将其用于 datepicker 初始化函数(beforeShowDay、changeMonthYear)。 我还有一些实用功能。

我被卡住了,因为我真的不知道如何继续。
我已经阅读了很多文章、教程、stackoverflow 线程——尤其是在 this 范围等方面,但现在我不知道从哪里开始!

这是我目前所拥有的:

var Calendar = (function() {
var obj = this;

var calendar = {
    datescache: [],
    bsd: function (date) {
        var offset =  this.formatNum(date.getMonth()+1)+'-'+this.formatNum(date.getDate());
        if (thedate[offset] != undefined) {
            return [true, 'bold', thedate[offset] + ' événement(s)'];
        } else {
            return [true];
        }
    },
    formatNum: function (i) {return ('0'+i).slice(-2);},
    getEventsForDate: function(year, month, inst) {
        var date = this.datescache;
        if (this.datescache[month] === undefined) {
            console.warn('uncached: '+month);
            $.ajax({
                url: '/event/get-event-count/year/'+year+'/month/'+month+'/format/json',
                success: function (resp) {
                    date[month] = resp.events;
                },
                async: false
            });
        }
        console.log('return: '+month);
        return date[month];
    }
}

return calendar;    
})();


$('#calendar').datepicker({
    dateFormat: "dd\/mm\/yy",
    showOtherMonths: true,
    selectOtherMonths: true,
    beforeShowDay: Calendar.bsd,
    onChangeMonthYear: Calendar.getEventsForDate,
});

当然我在这行有一个错误:

var offset =  this.formatNum(date.getMonth()+1)+'-'+this.formatNum(date.getDate());  

因为this指的是日期选择器对象,因为我们在一个回调函数beforeShowDay中,它负责将日期选择器实例作为this传递给函数。 但我需要this 来引用我的实用函数,例如formatNum

  • 我应该从哪里开始?
  • 尝试扩展datepicker 对象是否更好(尚未尝试)?

提前感谢您的帮助!

编辑 1

好的,有了更多的阅读和第一个答案,我设法得到了一些工作:

var Calendar = (function() {
  var calendar = function() {
    var self = this;

    this.datescache = [];

    this.bsd = function (date) {
       [[... I use for instance self.datescache ...  ]]
    }

    [[...]]

  };
  return new calendar();
})();

这似乎工作正常。

  • 还需要全局封装吗?

再次感谢!

【问题讨论】:

    标签: javascript jquery jquery-ui scope


    【解决方案1】:

    对于在回调和其他函数中操作this,有几个选项。

    而不是在函数内部调用this,您可以调用像thatself 这样的别名。在您的情况下,变量 obj = this 已经是别名,因此您可以调用 obj.formatNum

    另一个选项是Function.bind,它允许您这样做:

    foo : (function() {
        ...
    }).bind(obj),
    ...
    

    请注意,Function.bind 是 ES5 的东西。你可以使用 underscorejs 中的_.bind_.bindAll

    this 作用域工作的另一个选项是这样做

    beforeShowDay: function() {
        Calendar.bsd();
    },
    onChangeMonthYear: function() {
        Calendar.getEventsForDate();
    },
    

    这里的区别是传递一个函数(调用时将使用不同的this 对象调用)你传递一个调用你的函数的函数ON你自己的日历对象因此强制 thisCalendar

    见:

    var f = function() { console.log(this); }
    var a = {
        b: f
    };
    var c = {}
    c.d = a.b;
    c.e = function() {
        a.b();
    };
    
    f(); // window
    a.b(); // a
    c.d(); // c
    c.e(); // calls a.b(); so a
    

    this 范围是您调用该方法的任何对象。

    【讨论】:

    • 谢谢。正如您将在我的编辑中看到的那样,我在calendar 函数中转向了this.functionname 方法。看起来这样可以正常工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多