为了账号安全,请及时绑定邮箱和手机立即绑定

关于this和call的指向问题

关于this和call的指向问题

梵蒂冈之花 2019-03-15 15:15:36
问题一:我在一个构造函数里写了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);    },    }
查看完整描述

2 回答

  • 2 回答
  • 0 关注
  • 499 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号