Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to Use Prototype?

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 117
    Comment on it

    The application runs faster after the prototype property of the GameObject is defined. As a direct result, every instance of GameObject references the methods within GameObject.prototype, taking them as their own methods.

    // define the GameObject constructor function
    var GameObject = function(width, height) {
        this.x = Math.floor((Math.random() * myCanvasWidth) + 1);
        this.y = Math.floor((Math.random() * myCanvasHeight) + 1);
        this.width = width;
        this.height = height;
        return this;
    };
    
    // (re)define the GameObject prototype object
    GameObject.prototype = {
        x: 0,
        y: 0,
        width: 5,
        width: 5,
        draw: function() {
            myCanvasContext.fillRect(this.x, this.y, this.width, this.height);
        }
    };
    

    We can then instantiate the GameObject 100 times.

    var x = 100,
    arrayOfGameObjects = [];
    
    do {
        arrayOfGameObjects.push(new GameObject(10, 10));
    } while(x--);
    

    When we call the draw method, it will reference the exact same function.

    var GameLoop = function() {
        for(gameObject in arrayOfGameObjects) {
            gameObject.draw();
        }
    };
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: