簡體   English   中英

在js中傳遞類的實例並在沒有新實例的情況下訪問其方法

[英]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
  }
}

我只想在不創建新實例的情況下調用方法。

如果要在類中創建私有數據,請使用WeakMap或閉包。 this[name]根本不是私有的,任何可以訪問實例化對象的對象都可以完全看到它。

另一個問題是您的return this[name]; getName函數在范圍內沒有name變量。

同樣,在實例化對象本身之前不能訪問對象的類方法。

您可能需要這樣的東西:

 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM