0

Referencing a private member E.G. this.#rts() gives the error:

SyntaxError: Private field '#rts' must be declared in an enclosing class

Although when that line is evaluated, the function has been assigned to an instance method and this is correctly bound.
Is there a way to achieve this, I.E. to reference private members across files?

Note: I'm using Node 13.

Example:

import {Cpu6502} from "./cpu6502.mjs";
console.log((new Cpu6502).beq());

cpu6502.mjs:

import {beq} from "./instructions.mjs";
export class Cpu6502 {
    beq = beq // `this` is correctly bound
    #rts = () => "RTS"
}

instructions.mjs:

export function beq() {
    return this.#rts() // If this line references a public member instead,  
                       // it works fine and `this` is correctly bound.
}
Petruza
  • 11,744
  • 25
  • 84
  • 136
  • 2
    Please post your code *here*. – deceze Apr 14 '20 at 11:53
  • 1
    Please visit [help], take [tour] to see what and [ask]. Do some research, search for related topics on SO; if you get stuck, post a [mcve] HERE at SO of your attempt, noting input and expected output. – mplungjan Apr 14 '20 at 11:54
  • Any help here: https://stackoverflow.com/questions/58962695/how-to-define-private-methods-in-a-js-class ? – mplungjan Apr 14 '20 at 11:57
  • @mplungjan No, it doesn't address referencing the private member across files. – Petruza Apr 21 '20 at 13:40

1 Answers1

1

You can use this approach but probably you want somenthing like a mixin

import { lda } from './instructions.mjs'

export class Cpu6502 {
    constructor() {
       this.lda = lda.bind(this);
    }
    A = 0xFF
    #rts() {
        return "RTS";
    }
    ldx() {
        return this.lda();
    }
}`
  • I get this error: `SyntaxError: Unexpected token '(' at Loader.moduleStrategy (internal/modules/esm/translators.js:81:18)` – Petruza Apr 17 '20 at 11:42
  • 1
    What are you're using to transpile/bundle it?maybe you can try to move the A = 0xFF in the constructor. – Pasquale Mangialavori Apr 20 '20 at 09:40
  • I'm just running it with Node 13. And already removed A because it was a leftover of an old test _(still the same cryptic error)_, I just need to call a private method from a bound function declared in another file. – Petruza Apr 21 '20 at 13:09
  • 1
    Reading the code I can tell you is a little bit tricky what you're trying to do. https://codesandbox.io/s/async-breeze-wpjty?file=/src/index.js but this should be want you want. – Pasquale Mangialavori Apr 21 '20 at 13:59
  • Yeah I figured out the most common solution would be the underscore convention. – Petruza Apr 22 '20 at 14:18