[英]How to use THIS with OOP javascript?
我是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);
}
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.