开发者

Javascript object property inaccessible from another property (function)

Quick question, why does my reference to weekdays inside change_date() give weekdays is undefined error in Firebug?

I also tried this.weekdays, same.

How do I correct this?

var timesheet_common = {

    weekdays : ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],

    change_date: function() {
        $('#text_inpu开发者_如何学Pythont').val( weekdays[(new Date()).getDay()] );
    }

};


Use this.weekdays because it's an object.

Edit: I tried with this and it worked for me.


In JavaScript the function is not associated with its model. You might do sth like this:

var timesheet_common = (function(){

    var weekdays = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];

    var change_date = function() {
        $('#text_input').val( weekdays[(new Date()).getDay()] );
    };

    return { weekdays: weekdays, change_date: change_date }

})();


There are two problems with your code:

  1. Inside change_date() you should refer to weekdays as this.weekdays, because they're both defined in the same object.

  2. When you use change_date() as a click handler, you must use $.proxy(timesheet_common, 'change_date') instead; doing this makes sure change_date() is called within the context of timesheet_common rather than the clicked element.


function TimesheetCommon(){
    this.weekdays = ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"];
}
TimesheetCommon.prototype.change_date = function(){
     $('#text_input').val( this.weekdays[(new Date()).getDay()] );
}

var timesheet_common = new TimesheetCommon();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜