0

我正在尝试掌握“OOP”JavaScript 技术,今天我开始编写一个小型测试应用程序。基本上,它是一个游戏循环,每次更新坐标都会增加,以便 HTML 元素移动。

问题是我希望能够运行多个应用程序实例,因此我试图将实例数据存储在 中this,但是在我的构造函数和exec()方法中保存的内容在私有方法中不可用update()。似乎是什么官员,问题?

var Jsloth = (function () {
    var Jsloth = function () {
        var sloth = document.createElement('div');
        var attr = document.createAttribute('class');
        attr.value = 'sloth';
        sloth.setAttributeNode(attr);
        this.sloth = document.getElementsByTagName('body')[0].appendChild(sloth);
    };

    var exec = function () {
        this.x = 0;
        this.y = 0;
        var that = this;
        setInterval(function () {
            that.update();
        }, 1000/10);
    };

    var update = function () {
        this.x++;
        this.y++;
        this.sloth.style.left = this.x + 'px';
        this.sloth.style.bottom = this.y + 'px';
    };

    Jsloth.prototype.constructor = Jsloth;
    Jsloth.prototype.exec = exec;
    Jsloth.prototype.update = update;

    return Jsloth;
})();

var sloth1 = new Jsloth();
sloth1.exec();

编辑:使用有效的解决方案更新代码!

4

2 回答 2

3

在 JavaScript 中,this(几乎)完全取决于您如何调用函数,而不是在哪里/如何定义它。

你打电话的方式update

update();

...this将是全局对象(window在浏览器上),或者undefined如果您使用"use strict".

this在 范围内设置update,请使用callapply

update.call(this);
// or
update.apply(this);

更多(在我的博客上)

于 2013-05-04T23:04:38.927 回答
2

您尚未添加update到原型中。该方法中的值this很可能是window对象。

从此更改您的电话:

update();

对此:

update.call(this);

或添加update.prototype

Jsloth.prototype.update = update;

并使用:

this.update();

但是,如果您要从 调用update(),则setInterval()需要确保正确的this值。

为此,您可以传递一个匿名函数,并this在变量中保留对外部值的引用。

var exec = function () {
    this.x = 0;
    this.y = 0;
    var that = this;
    setInterval(function() {
        that.update();
      //update.call(that); // if you didn't add update() to the .prototype
    }, 1000/10);
};
于 2013-05-04T23:03:51.853 回答