0

Hi i want to call a method in another method of the same class.

// authentication.js
var Usermgmt = require('./usermgmt');
class authentication extends Usermgmt {
    #session = New Object();
    constructor() {
      super();
    }
    auth(username, password) {
      console.log(value);
      return true;
    }
    _setSession() {
      this.#session.name = "Session Name";
      this.test();
    }
}
module.exports = authentication;
// usermgmt.js
class usermgmt {
    constructor() {
    }
    test(){
        console.log("test parent");
        return "test";
    }
}

module.exports = usermgmt;
// index.js
var authentication = require('authentication');
let auth = new authentication();
if(auth.auth(req.body.username, req.body.password)) {
   console.log("all fine");
}

I get the error TypeError: Cannot read property '_B' of null

Any idea to avoide this? Also i want to call a function in the parent class.

Also find this example https://rfrn.org/~shu/2018/05/02/the-semantics-of-all-js-class-elements.html

class Ex22_Base {
  #privateMethod() { return 42; }
}

class Ex22_Sub extends Ex22_Base {
  #privateMethod() {
    assertThrows(() => super.#privateMethod(), TypeError);
  }

  #privateMethodTwo() {
    this.#privateMethod();
  }

  publicMethod() {
    this.#privateMethodTwo();
  }

  constructor() {
    this.#privateMethod();
  }
}

Thats is what i want to do. But the # don't work in my class and i get SyntaxError: Unexpected token '('

and when i call a method in method of the same class i get TypeError: Cannot read property of null

user3807340
  • 143
  • 1
  • 9
  • How do you call object of 'class' `A` (being aware of the fact that JS des not actually know structural classes but provides the 'class' keyword as syntactic sugar) ? – collapsar Apr 22 '20 at 22:59
  • Your problem is likely with how you call the `A()` method. If you show that particular code, we can help you better correct things. If you call it `a.A()` where `a` is an instance of `A`, it will work. But, if you pass `a.A` as a function reference or as a callback and let something else call it, it will not work properly without making some adjustments to the calling code. Please show us the calling code. – jfriend00 Apr 23 '20 at 02:31
  • ok i edit it. Maybe there is now a better understanding. The _setSession method get more complex and i would avoid double code. Another problem is #setSession as private method don't work. From ECMAScript ist should be work https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Classes/Class_fields – user3807340 Apr 23 '20 at 06:01

1 Answers1

1

It looks fine, you need to instantiate a new copy of A and call the A method on the class.

class A {
    constructor() {
    }
    _B(value) {
      console.log(value);
    }
    A() {
      this._B("test");
    }
}


const a = new A()

a.A() // test
Tom
  • 2,543
  • 3
  • 21
  • 42