Sarath  Kumar Rajendran
Sarath Kumar Rajendran

Reputation: 426

Passing instance of a class in js and accessing their methods without new instance

class A{
  constructor(name){
     this[name] = name ; //to be private so i need this
     new B(this);
  }
  getName(){
    return this[name];
  }
}
class B(){
  constructor(a){
     a.getName()// I wants to be like this
  }
}

I just want to call the methods without creating a new instance.

Upvotes: 1

Views: 1590

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370679

If you want to make private data in a class, either use a WeakMap or a closure. this[name] is not private at all, it's completely visible to anything that has access to the instantiated object.

Another problem is that with your return this[name];, the getName function does not have the name variable in scope.

Also, an object's class methods can't be accessed before the object itself is instantiated.

You might want something like this instead:

const A = (() => {
  const internals = new WeakMap();
  return class A {
    constructor(name) {
      internals.set(this, { name });
    }
    getName() {
      return internals.get(this).name;
    }
  }
})();
class B {
  constructor(a) {
    console.log(a.getName())
  }
}

const a = new A('bob');
const b = new B(a);

Upvotes: 2

Related Questions