从另一个属性(函数)无法访问Javascript对象属性

时间:2010-07-04 16:46:54

标签: javascript jquery variables scope

快速提问,为什么我在weekdays内引用change_date()会在Firebug中出现weekdays is undefined错误?

我也试过this.weekdays,同样。

我该如何纠正?

var timesheet_common = {

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

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

};

4 个答案:

答案 0 :(得分:1)

使用this.weekdays,因为它是一个对象。

编辑:我尝试使用this,它对我有用。

答案 1 :(得分:1)

在JavaScript中,该函数与其模型无关。你可能会这样做:

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 }

})();

答案 2 :(得分:0)

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();

答案 3 :(得分:0)

您的代码存在两个问题:

  1. change_date()内,您应将weekdays称为this.weekdays,因为它们都在同一个对象中定义。

  2. 当您使用change_date()作为点击处理程序时,您必须使用$.proxy(timesheet_common, 'change_date')代替;这样做可确保在change_date()的上下文中调用timesheet_common而不是单击的元素。