問題一:我在一個構造函數里寫了setTime()方法和moveSnake方法,在setTime()里面用setInterval調用moveSnake方法,此時為什么this指向的是window?問題二: 我在setTime()里面用setInterval(this.moveSnake.call(Snake),500);為什么返回的是而不是,我依然不能console.log(this.snakeArr)。但是換了這種(function(theThis){ var that = theThis; that.timer = setTimeout(function() { that.moveSnake(); }, 500);})(this);就能讓this指到Snake這個構造函數呢?那為什么我直接把this當成參數傳給setTimeout不行呢:var timeTest = setTimeout(function(this) { this.moveSnake(); },500);這個樣子就是Unexpected token this了以下是這一部分的代碼,其他不相關的沒有貼出:function Snake(id, score, speed, x, y){ this.id = document.getElementById(id); this.ctx = this.id.getContext("2d"); this.cellWidth = 10; //每個格子的大小 this.score = document.getElementById(score); this.speed = document.getElementById(speed); this.x = x; this.y = y; // 畫canvas大小 this.id.width = this.x * this.cellWidth; console.log(this.id.width); this.id.height = this.y * this.cellWidth; this.id.style.border = "1px solid black"; this.setDirection();}Snake.prototype = { init: function() { this.snakeArr = [[1,parseInt(this.y/2)],[2,parseInt(this.y/2)]]; //蛇身長度。初始化時只有兩個長度,每一個點存了[x,y]兩個坐標,parseInt(this.y/2)是整個canvas的中間取整,length/push的是蛇頭,unshift的是蛇尾 this.foodPosition = []; //儲存當前食物的位置,這里每次都初始化為0 this.direction = 1; //方向:右1,下2,左3,上4 //畫畫布 this.ctx.fillStyle ="#fff"; this.ctx.fillRect(0,0,this.cellWidth*this.x,this.cellWidth*this.y); this.drawSnake(); //記得寫this this.drawFood(); this.setTime(); }, //蛇的移動 moveSnake: function(){ console.log(this); //window console.log(this.snakeArr); }, //定時器 setTime: function() { // setTimeout(this.moveSnake.call(Snake),500); //為什么這樣指過去不行? (function(theThis){ var that = theThis; that.timer = setTimeout(function() { that.moveSnake(); }, 500); })(this); }, }
關于this和call的指向問題
梵蒂岡之花
2019-03-15 15:15:36