views:

57

answers:

3

Hi,

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_input').val( weekdays[(new Date()).getDay()] );
    }

};
+1  A: 

Use this.weekdays because it's an object.

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

tur1ng
i get 'this.weekdays is undefined'
Obay
run in Firebug - `var timesheet_common = { weekdays : ["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],change_date: function() {console.log(this.weekdays);}};timesheet_common.change_date();`
Russ Cam
Russ, it says `undefined`
Obay
The exact code above, when run in Firebug says `undefined`? Hmm, that sounds like there's something wrong with your Firebug then :) The function context of the anonymous function assigned to the `change_date` property in the given code is the object literal to which the property belongs. What does it say if you replace `this.weekdays` with `this`?
Russ Cam
@Obay Don't confuse the return value with the log message (ie in Chrome Dev Tools). It definitely works.
stefanw
+1  A: 

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 }

})();
Marek Kowalski
A: 
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();
Jan Kuča
wow i didn't know you could make objects like that in javascript. what's happening here? how come you can already call a `new` on TimesheetCommon? which part of that code turned TimesheetCommon into an object that is `new`-able?
Obay
Every function creates an object when called with new. Add methods to the prototype property as shown above.
Jan Kuča