在Constructor JavaScript中初始化属性

时间:2016-05-09 16:42:24

标签: javascript constructor properties initialization

我正在尝试初始化对象构造函数中的属性,但是当我尝试访问它时,看起来该属性未定义为初始化。

当功能' applyGravity'被称为第二个' if(this._yPos< 200)' 返回false,因为this._yPos未定义且未定义< 200 = false而不是执行" this._yPos + = this._gravity;" 代码, ._ yPos = 200; this._isJumping = false; 已执行。

这是我的代码:

var Rabbit = (function () {
    function Rabbit(name) {
        this._name = name;
        this._yPos = 0;
        this._gravity = 20;
        this._jumpForce = 0;
        this._isJumping = false;
    }

    Rabbit.prototype.normalJump = function () {
        this._isJumping = true;
        this._jumpForce = this._gravity;
    };

    Rabbit.prototype.turboJump = function () {
        this._isJumping = true;
        this._jumpForce = this._gravity * 2;
    };

    Rabbit.prototype.applyGravity = function () {
        console.log(this._yPos);
        if(this._isJumping) {
            this._yPos -= this._jumpForce;
            this._jumpForce--;
        }

        if(this._yPos < 200) {
            this._yPos += this._gravity;
        } else {
            this._yPos = 200;
            this._isJumping = false;
        }
        console.log(this._yPos);
    };

    return Rabbit;
}());

var rabbit = new RabbitGame.Rabbit('pesho');
console.log(rabbit._yPos);
setInterval(rabbit.applyGravity, 300);

0 个答案:

没有答案