对象JavaScript,无法读取未定义的属性...这是之前读过的

时间:2015-10-28 17:01:30

标签: javascript css object

我尝试制作一个每秒随机移动,调整大小和更改div颜色的对象。

在我的经典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");

它有效一次,在我收到错误后#34;无法读取属性&#c;&#39;未定义&#34;。我试图以多种方式重写它,但我无法找到解决方案。

你能解释我的错误吗?

谢谢=)

1 个答案:

答案 0 :(得分: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"); 因为执行上下文已更改

Set btn = ThisWorkbook.Sheets("Navigation").Buttons.Add(rng.Left, rng.Top, rng.Width, rng.Height * 2)