我想实现什么目标?
我有一个名为 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.name
是 result
?
最佳答案
您需要在构造函数内创建 this.i = 1;
属性:
var Looper = function () {
this.i = 1;
console.log('Created Looper Object...');
}
在您当前的代码中 this
keyword引用全局对象(window
),因此您实际上正在创建一个全局变量(这是某种“静态”,是的)。
类似的事情发生在从 setInterval
调用的函数中, this
再次设置为全局对象(这就是它找到数字的原因)。您需要明确 call Looper
实例上的 loop
方法,例如通过
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 classes ,并且 this
的工作方式与 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;
});
关于javascript - OOP Javascript,为什么这个对象不能按预期工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15951465/