JavaScript - “这个"指向 Window 而不是对象 [英] JavaScript - "this" pointing to Window instead of object
问题描述
我第一次面对 JavaScript 中的 OOP 以及随之而来的所有麻烦......
I'm facing for the first time OOP in JavaScript and all the troubles that comes with it...
我有这个函数/对象/类/任何有一个方法 mainLoop()
应该显示一些下降的文本 - 就像在电影 The Matrix 中一样.当我调用它时,虽然我得到未定义的变量错误并使用调试器,但我看到 mainLoop()
this
指向 Window
而不是调用方法的对象.
I have this function/Object/class/whatever which has a method mainLoop()
that should display some falling text - just like in the movie The Matrix. When I call it though I get undefined variables errors and using the debugger I see that inside mainLoop()
this
is pointing to Window
instead of the object that called the method.
代码如下:
function Matrix(config) {
return {
//[...lots of other vars...],
drops: [],
lines: [],
//final string to put in the container
str: "",
mainLoop: function(){
var tmp = "";
//randomly create a "character drop"
//(not if there's already a drop)
for(var i = 0; i < this.cols; i++){
if(this.drops[i] == 0 && Math.random() < this.freq){
this.drops[i] = irandom(this.rows) + 1;//new drop
tmp += randomChar();//output drop
}
else tmp += lines[0].charAt(i);
}
this.lines[0] = tmp; // <-------------- ERROR
//update already created drops
tmp = "";
for(var j = 0; j < this.cols; j++){
if(this.drops[j] > 0){
tmp += this.randomChar();
this.drops[j]--;
}
else tmp += " ";
}
this.lines[this.rowIndex] = tmp;
this.rowIndex = (this.rowIndex+1) % this.rows;
//render the entire text
this.str = "";
for(var l in this.lines)
this.str += l + "<br/>";
$(container).html = this.str;
},
start: function(){
for(var i = 0; i < this.cols; i++)
this.drops[i] = 0;
timer = setInterval(this.mainLoop ,this.delay);
},
stop: function(){
clearInterval(this.timer);
},
randomChar: function(){
return this.chars.charAt(irandom(this.chars.length));
},
irandom: function(x){
return Math.floor(Math.random()*x);
}
}
};
然后我像这样调用这个函数:
And then I call this function like this:
var config = {
container: "#container",
rows: 20,
cols: 20,
delay: 2000
};
var m = Matrix(config);
m.start();
浏览器控制台说:
TypeError: this.lines is undefined
(代码注释显示了错误的确切点).此外,调试器说,在这一点上,this
指向 Window
,而不是像我期望的那样指向 m
......有什么问题我的推理?在此先感谢您的帮助.
(code comment shows the exact point of the error). Furthermore, the debugger says that, at that point, this
points to Window
, not to m
as I would expect... what's wrong with my reasoning? Thanks in advance for any help.
推荐答案
改变你的 start
函数:
start: function(){
var self = this;
for(var i = 0; i < this.cols; i++)
this.drops[i] = 0;
timer = setInterval(function() {
self.mainLoop();
}, this.delay);
}
this
指向 window
因为范围已经改变.
this
was poiting at window
because the scope has changed.
这篇关于JavaScript - “这个"指向 Window 而不是对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!