[英]Javascript - Prototype is not reading constructor variables
我在從原型函數中的對象訪問公共變量時遇到問題...據我所讀,這應該可行,但是也許有經驗的人可以指出我在做什么錯。
在這種情況下,我試圖編寫自己的動畫對象,並具有其他管理員可以使用的自我刪除功能。 callback是寫為字符串的命令,x&y是開始位置,x2,&y2是結束位置,time是以秒為單位的時間,element是移動的元素。 doTime是基准測試函數的結果,該基准測試函數在頁面加載時執行以正確設置timeOut偏移量。
我可以創建帶有內部函數的工作版本,但是由於多次創建此對象,因此我想對函數進行原型設計以提高創建速度。
測試表明this.vars都沒有在原型函數中讀取。
function circDelta(progress) {
if (progress < .5)
return (1 - Math.sin(Math.acos(progress))) / 2
else
return (2 - (1 - Math.sin(Math.acos(2*(1-progress))))) / 2
}
function animation(element,x,y,x2,y2,time,callback){
this.e = element;
this.x = x;
this.y = y;
this.x2 = x2;
this.y2 = y2;
this.t = time * 1000;
this.c = callback;
this.cT = 0;
this.id = setTimeout(this.frame, doTime);
}
animation.prototype.frame = function(){
this.cT+=doTime;
if(this.cT>=this.t)
{
this.e.style.left = this.x2+'px';
this.e.style.top = this.y2+'px';
if(typeof this.c === 'function')
this.c();
}
else
{
this.e.style.left = ((this.x2-this.x)*circDelta(this.t/this.cT))+this.x+'px';
this.e.style.top = ((this.y2-this.y)*circDelta(this.t/this.cT))+this.y+'px';
this.id = setTimeout(this.frame, doTime);
}
};
我正在使用這樣的功能:
this.curr_anim = new animation(hC.menus[0],0,0,0,30,1.5,hC.anim_finished);
任何幫助將不勝感激....在此先感謝您。
您可能會在setInterval
調用中遇到范圍界定問題,
因為setInterval將在指定的時間間隔之后並以window對象的范圍被調用,所以它將無法使用此方法訪問對象數據,
因此您需要使用局部變量傳遞對象的引用,可以通過使用setInterval中的閉包來實現此目的
var me = this;
this.id = setTimeout(function() {
me.frame();
}, doTime);
因此您的最終代碼將如下所示
function circDelta(progress) {
if (progress < .5)
return (1 - Math.sin(Math.acos(progress))) / 2
else
return (2 - (1 - Math.sin(Math.acos(2*(1-progress))))) / 2
}
function animation(element,x,y,x2,y2,time,callback){
this.e = element;
this.x = x;
this.y = y;
this.x2 = x2;
this.y2 = y2;
this.t = time * 1000;
this.c = callback;
this.cT = 0;
var me = this;
this.id = setTimeout(function() {
me.frame();
}, doTime);
}
animation.prototype.frame = function(){
this.cT+=doTime;
if(this.cT>=this.t)
{
this.e.style.left = this.x2+'px';
this.e.style.top = this.y2+'px';
if(typeof this.c === 'function')
this.c();
}
else
{
this.e.style.left = ((this.x2-this.x)*circDelta(this.t/this.cT))+this.x+'px';
this.e.style.top = ((this.y2-this.y)*circDelta(this.t/this.cT))+this.y+'px';
var me = this;
this.id = setTimeout(function() {
me.frame();
}, doTime);
}
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.