OOP Javascript,为什么这个对象不能像预期的那样工作?

时间:2013-04-11 14:31:00

标签: javascript oop object

我想达到什么目的?

我有一个名为Looper的课程。我想给每个对象一个名字和一个自己的looper。

我期待的结果

Created Looper Object...
one
Created Looper Object...
two
one - 1
two - 1
one - 2
two - 2
one - 3
two - 3
one - 4
two - 4
one - 5
two - 5
.......

我的代码

使用此代码我希望它能够正常工作..

var Looper = (function (window, document, $) {

    this.i = 1;

    var Looper = function () {
        console.log('Created Looper Object...');
    }

    var getName = function () {
        return this.name;
    }

    var setName = function (newName) {
        this.name = newName;
    }

    var loop = function () {
        console.log(getName() + ' - ' + this.i);
        this.i = this.i + 1;
    }

    var startLoop = function () {
        window.setInterval(loop, 1000);
    }

    Looper.prototype = {
        getName: getName,
        setName: setName,
        start: startLoop
    }

    return Looper;
})(window, document, jQuery);

var one = new Looper();
one.setName('one');
console.log(one.getName());
one.start();

var two = new Looper();
two.setName('two');
console.log(two.getName());
two.start();

jsFiddle example

我的结果

但它没有......

Created Looper Object...
one
Created Looper Object...
two
result - 1
result - 2
result - 3
result - 4
result - 5
.......

有人可以告诉我它为什么没有吗?

我的问题是可以为每个对象设置this.name

但我无法为每个对象设置this.i。他们超越对方i。看起来this.i是静态的?!?!?

当我使用console.log(two.getName());时,它也有效。但是在循环中this.nameresult

1 个答案:

答案 0 :(得分:2)

您需要在构造函数中创建this.i = 1;属性:

var Looper = function () {
    this.i = 1;
    console.log('Created Looper Object...');
}

在您当前的代码中,this keyword引用全局对象(window),因此您实际上是在创建一个全局变量(这是某种“静态”,是的)。

在从setInterval调用的函数中发生了类似的事情,this再次被设置为全局对象(这就是它根本找到数字的原因)。您需要在loop实例上明确call Looper方法,例如

var startLoop = function () {
    var that = this;
    window.setInterval(function() {
       loop.call(that); // "that" refers to the Looper object, while "this" does not
       // if "loop" were a method on the Looper, it's equivalent to
       // that.loop()
    }, 1000);
}

或通过bind

var startLoop = function () {
    window.setInterval(loop.bind(this), 1000);
}

此外,在loop函数中,您需要调用getName作为当前Looper对象的方法:

this.getName()

似乎增加了一点混淆,即所有函数/方法不仅可以在对象的(继承)属性上访问,还可以作为模块中的局部变量。请注意JavaScript has no classesthis在Java中不起作用 - 您始终需要明确区分变量和属性。您的模块看起来应该更像这样:

var Looper = (function() {

    function Looper() {
        this.i = 1;
        this.name = null;
        console.log('Created Looper Object:', this);
    }

    Looper.prototype.getName = function() {
        return this.name;
    };
    Looper.prototype.setName = function(newName) {
        this.name = newName;
    };
    Looper.prototype.start = function() {
        var that = this;
        window.setInterval(function() {
            console.log(that.getName() + ' - ' + that.i);
            that.i++;
        }, 1000);
    };

    return Looper;
});
相关问题