Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Correct usage of "this" in assemblyscript #2849

Open
johnhill396 opened this issue Jun 13, 2024 · 4 comments
Open

Correct usage of "this" in assemblyscript #2849

johnhill396 opened this issue Jun 13, 2024 · 4 comments
Labels

Comments

@johnhill396
Copy link

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?

@CountBleck
Copy link
Member

I'm pretty sure this is okay.

@HerrCai0907
Copy link
Member

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

@johnhill396
Copy link
Author

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

yeah, that's what I was worried about. Could that cause any issues at runtime? Any best practices around it?

@MaxGraey
Copy link
Member

MaxGraey commented Jun 14, 2024

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()
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

4 participants