如何使用OOP javascript进行此操作?

时间:2014-01-04 12:24:35

标签: javascript oop

我是JavaScript新手,只是尝试用PHP做同样的事情。在下面的例子中,我不能使用THIS关键字一般调用类Screen的getMyWeekDay()方法,我在原型函数中要做的就是调用我的“Screen”类的特定实例(即我的实例)被称为“屏幕”)这种目的有点破坏......

我想我刚刚在设计中犯了一个新手错误?

//Our screen object
function Screen() {}

//update the clock element on the screen
Screen.prototype.updateClock = function(date) {
    //do some stuff
    $('#dateContainer').html(screen.getMyWeekDay(date)+' '+date);
    //Here I would prefer    $('#dateContainer').html(this.getMyWeekDay(date)+' '+date);
}

//return the day name in swedish
Screen.prototype.getMyWeekDay = function(d) {
    var d=new Date(d);
    var weekday=new Array(7);
    weekday[0]="Söndag";
    weekday[1]="Måndag";
    weekday[2]="Tisdag";
    weekday[3]="Onsdag";
    weekday[4]="Torsdag";
    weekday[5]="Fredag";
    weekday[6]="Lördag";
    var n = weekday[d.getDay()];
    return n;
}

screen = new Screen();

//use the new instance (screen) of class Screen

- 更新 -

我意识到我的问题可能超出了我分享的代码,使用了建议的解决方案。

这是我的整个代码,我只是试图饶了你一堆我认为不必要的阅读......

Screen.prototype.updateClock = function() {

    var jqxhr = $.get('{{ path('getClock') }}')
      .success(function(data) { 
            time = data.substring(data.indexOf("|")+1, data.indexOf("|")+6);
            date = data.substring(0, data.indexOf("|"));

            $('#timeContainer').html(time);          

            try{
                //see if template has its own function for date rendering...
                template_date_format(getMyWeekDay(date),date);
            }
            catch(e) {
                //standard fallback if not
                $('#dateContainer').html(this.getMyWeekDay(date)+' '+date);
            }       
       })
      .error(function() {
            console.log('there was an error fetching clock data');
      });        
            setTimeout(function() {
              updateClock();
            }, 15000);          

}

1 个答案:

答案 0 :(得分:0)

Screen.prototype.updateClock = function() {

var oopThis = this;

var jqxhr = $.get('{{ path('getClock') }}')
    .success(function(data) { 

        // the log line below will return an object which contains the ajax calls options
        console.log(this);

        time = data.substring(data.indexOf("|")+1, data.indexOf("|")+6);
        date = data.substring(0, data.indexOf("|"));

        $('#timeContainer').html(time);          

        try {
            //see if template has its own function for date rendering...
            template_date_format(getMyWeekDay(date),date);
        } catch(e) {
            //standard fallback if not
            $('#dateContainer').html(oopThis.getMyWeekDay(date)+' '+date);
        }    
    })
    .error(function() {
        console.log('there was an error fetching clock data');
    });        

    setTimeout(function() {
        oopThis.updateClock();
    }, 15000);
}

行。根据您在this函数的上下文中的ajax/get/post上面的代码,引用包含其选项的ajax对象。

BTW,常见的惯例是var self = this;