[英]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. 我只想在不创建新实例的情况下调用方法。
If you want to make private data in a class, either use a WeakMap or a closure. 如果要在类中创建私有数据,请使用WeakMap或闭包。
this[name]
is not private at all, it's completely visible to anything that has access to the instantiated object. this[name]
根本不是私有的,任何可以访问实例化对象的对象都可以完全看到它。
Another problem is that with your return this[name];
另一个问题是您的
return this[name];
, the getName
function does not have the name
variable in scope. ,
getName
函数在范围内没有name
变量。
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.