Javascript OOP可见性

时间:2017-03-07 21:05:39

标签: javascript canvas

大家好我有这个代码

class Player {
                        constructor(posX, posY, spdX, spdY, width, height, image){
                            // Vytvoření hráče
                            this.posX = posX;
                            this.posY = posY;
                            this.spdX = spdX;
                            this.spdY = spdY;
                            this.width = width;
                            this.height = height;
                            this.image = image;
                        }     
                        // Draws player
                        draw(){
                            var imageObj = new Image();
                            imageObj.src = this.image;
                            ctx.drawImage(imageObj, testPlayer.posX, testPlayer.posY);
                        }
                        jump(){
                            this.move('up');

                        }
                        // Move
                        move(direction){
                            // Returns false if fails
                            switch(direction){
                                case 'right':
                                    this.posX+= this.spdX;
                                    break;
                                case 'left':
                                    this.posX-= this.spdX;
                                    break;
                                case 'up':
                                    this.posY-= this.spdY;
                                    break;
                                case 'down':
                                    this.posY+= this.spdY;
                                    break;
                                default:
                                    return false;
                            }
                        }
                    }

我在跳转方法方面有问题。 当我想跳,我必须上下,但我怎么能在一段时间后这样做。 因为我尝试setTimeout(function(){})但在函数关键字内部,这个方法无法看到方法移动。如果我做setTimeout(this.move('down'),500)它不起作用。那么任何想法?

2 个答案:

答案 0 :(得分:2)

您需要具有正确上下文的功能。一种简单的方法是使用ES6箭头函数(caniuse)。它们将保留您最初定义函数时的this上下文:

setTimeout(()=>{this.move('down')}, 500)

或者,如果要使用常规函数,请使用Function.prototype.bind()绑定this上下文。这样,当最终调用函数时,上下文是你调用.bind(this)时的this

function goDown(){this.move('down')}
setTimeout(goDown.bind(this))

答案 1 :(得分:1)

问题在于setTimeout callback会导致this的值发生变化。

您可以通过以下方式保留this

var that = this;
setTimeout(function () {
    that.move('down');
}, 500);