Skip to content

Feature Request: Make all functions declared in a GameObject methods of the GameObject #5

@jcollard

Description

@jcollard

I think it would be convenient to have all of the functions declared within a GameObject be methods of the GameObject. Currently, the start and update functions are actually methods of the GameObject. However, all other functions are methods of the Window. Here is a simple example demonstrating the current functionality:

  // It would be nice to have functions become methods of the
  // object. I am using a self = this hack and adding member
  // variables which also is slightly broken.

// called once when the game starts
function start() {
  this.hp = 8;
}

// called every frame
function update() {
  // This is a method of the GameObject
  if (isKey('q'))
    say(`I have ${this.hp} hp`);
  
  if (isKey('w'))
    notAMethod();
    
  if (isKey('e'))
    pythonStyleMethod(this);
  
  
}

function notAMethod() {
  // `this` is the Window object
  say(`I have ${this.hp} hp`);
}

function pythonStyleMethod(self) {
  say(`I have ${self.hp} hp`);
}

It isn't completely necessary to add this as there are work arounds. For example, in the start method you can declare a method and forward it to a function. At that point, the this keyword will work in the context of update. BUT it will not work in the context of any other methods. In the example below, there is a workaround to declare a GameObject variable self which can be used throughout all of the functions. It feels a little bit hacky but could potentially be the way Code train handles "public / private" methods and fields.

let self;

function start() {
  this.hp = 8;
  this.addMethod = notAMethod;
  self = this; 
}


function notAMethod() {
  // `this` is the Window object
  say(`I have ${this.hp} hp`);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions