未捕获的TypeError:无法读取属性' style'未定义的对象

时间:2014-12-20 15:10:03

标签: javascript error-handling

我不知道我在这里失踪了什么,请你帮助我。

这是我的代码:

<!DOCTYPE html>    
<html>
<head>
    <title>SNOW</title>
    <meta charset="UTF-8">
</head>
<body>  
<div id="snowDiv">*</div>
</body>
<script>
    var SNOW = function () {
        this.top = 0;
        this.left = 0;
        this.snowflake = document.getElementById('snowDiv');
        this.snowflake.style.margin         = this.top+'px 0px 0px '+this.left+'px';
        this.snowflake.style.positon        = 'absolute';
        this.snowflake.style.zIndex         = '1';
        this.snowflake.style.position       = 'absolute';
        this.snowflake.style.height         = '5px';
        this.snowflake.style.width          = '5px';
        this.moveSnow = function () {
            SNOW.top += 2;
            SNOW.left += 5;
            SNOW.snowflake.style.margin = SNOW.top+'px 0px 0px '+SNOW.left+'px';
            window.requestAnimationFrame(SNOW.moveSnow);
        };
    };
    var snowing = new SNOW();
    snowing.moveSnow();
</script>

如果我将moveSnow函数放在SNOW对象之外它可以正常工作,但就像它没有那样。

2 个答案:

答案 0 :(得分:0)

这是因为SNOW引用了对象构造函数,而不是this引用的实例。创建一个引用this的变量,即that = this。现在,您可以将方法应用于方法中的实例。

 var SNOW = function () {
    this.top = 0;
    this.left = 0;
    this.snowflake = document.getElementById('snowDiv');
    this.snowflake.style.margin         = this.top+'px 0px 0px '+this.left+'px';
    this.snowflake.style.positon        = 'absolute';
    this.snowflake.style.zIndex         = '1';
    this.snowflake.style.position       = 'absolute';
    this.snowflake.style.height         = '5px';
    this.snowflake.style.width          = '5px';
    var that = this;
    this.moveSnow = function () {
        that.top += 2;
        that.left += 5;
        that.snowflake.style.margin = that.top+'px 0px 0px '+that.left+'px';
        window.requestAnimationFrame(that.moveSnow);
    };
};
var snowing = new SNOW();
snowing.moveSnow();
<div id="snowDiv">*</div>

答案 1 :(得分:0)

这是你的可变范围的问题.... 在这里查看jsbin链接...     http://jsbin.com/keyaze/1/edit?html,output