assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Correct usage of "this" in assemblyscript

Open johnhill396 opened this issue 1 year ago • 4 comments

Question

I'm working on an AssemblyScript application. The way the code is structured requires passing an instance of a class in the constructor of another class. For example:

class Something {

  constructor(private context: MyContext) { }

  testMethod(): void {
    //Some logic which uses variables and methods from context class  
    let a: this.context.getSomething();
  }
}

class MyContext {
  
  //Is below a correct usage of 'this'?
  somethingObj: Something = new Something(this);

  myMethod(): void {
    //Some logic which uses somethingObj
    this.somethingObj.testMethod()
  }
  
}

I'm able to build and run the code successfully. But, is the above field somethingObj in MyContext class correctly using 'this' keyword? Could this somehow lead to some runtime errors around out of bounds memory access?

johnhill396 avatar Jun 13 '24 15:06 johnhill396

I'm pretty sure this is okay.

CountBleck avatar Jun 13 '24 15:06 CountBleck

It is ok. But you should note that this is not initialized at this moment.

HerrCai0907 avatar Jun 13 '24 16:06 HerrCai0907

You can just use this as alterative:

class MyContext {
  somethingObj: Something!; // use exclamation mark

  constructor() {
    this.somethingObj = new Something(this)
  }

  myMethod(): void {
    this.somethingObj.testMethod()
  }
}

MaxGraey avatar Jun 14 '24 15:06 MaxGraey

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in one week if no further activity occurs. Thank you for your contributions!

github-actions[bot] avatar Jul 14 '24 23:07 github-actions[bot]