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:
Inside
change_date()
you should refer toweekdays
asthis.weekdays
, because they're both defined in the same object.When you use
change_date()
as a click handler, you must use$.proxy(timesheet_common, 'change_date')
instead; doing this makes surechange_date()
is called within the context oftimesheet_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();
精彩评论