2015-10-28 31 views
0

我嘗試製作一個對象,每秒隨機移動一個div,調整其大小並更改其顏色。對象JavaScript,無法讀取未定義的屬性...之前只讀

在我的古典HTML頁面有

<div id="Rectangle1"></div> 

這裏是我的代碼

var colors = ["red","yellow","blue","dark","green","pink","purple"]; 

function Rectangle(tag){ 

    this.moveNShape = function() { 
     //Defining new values 
     this.width = Math.floor(Math.random()*250)+50; 
     this.height = Math.floor(Math.random()*250)+50; 
     this.x = Math.floor(Math.random()*400)+100; 
     this.y = Math.floor(Math.random()*400)+100; 
     this.color = colors[Math.floor(Math.random()*7)]; 
     //Update the view 
     this.tag.css("position","absolute").css("height",this.height).css("width",this.width).css("left",this.x).css("top",this.y); 
     this.tag.css("backgroundColor",this.color); 
     //Launch again 
     setTimeout(this.moveNShape,1000); 

    } 

    this.tag = $('#'+tag); 
    this.moveNShape(); 

} 

var rect1 = new Rectangle("Rectangle1"); 

它的工作原理一次後,我得到錯誤「無法讀取的未定義的屬性‘CSS’」。我試圖用很多方式重寫它,但我找不到解決方案。

你能解釋我的錯誤嗎?

謝謝=)

+0

哪條線是你收到的錯誤?你有幾個電話到'.css'。 – ssube

回答

2

使用bindthis變量設置爲Rectangle對象。

你得到這樣的錯誤之前當moveNShape被稱爲經setTimeout究其原因,this成爲window,因爲執行環境發生了變化

var colors = ["red","yellow","blue","dark","green","pink","purple"]; 

    function Rectangle(tag){ 

     this.moveNShape = function() { 
      //Defining new values 
      this.width = Math.floor(Math.random()*250)+50; 
      this.height = Math.floor(Math.random()*250)+50; 
      this.x = Math.floor(Math.random()*400)+100; 
      this.y = Math.floor(Math.random()*400)+100; 
      this.color = colors[Math.floor(Math.random()*7)]; 
      //Update the view 
      this.tag.css("position","absolute").css("height",this.height).css("width",this.width).css("left",this.x).css("top",this.y); 
      this.tag.css("backgroundColor",this.color); 
      //Launch again 
      setTimeout(this.moveNShape.bind(this),1000); 

     } 

     this.tag = $('#'+tag); 
     this.moveNShape(); 

    } 

    var rect1 = new Rectangle("Rectangle1"); 
相關問題