簡體   English   中英

將屬性引用從一類傳遞到另一類

[英]Pass property reference from one class to another

說我有2類AuthClient 如果我具有Auth.token屬性,我希望能夠將該屬性作為參考傳遞給Client.token ,這樣,當我更改Auth.token它也會更改Client.token的值。

這是一個目前無法使用的簡化示例。

class Auth {
  constructor() {
    this._token = '123';
  }
  get token() {
    return this._token;
  }
  updateToken(newToken) {
    this._token = newToken;
  }
}

class Client {
  constructor(token) {
    this._token = token;
  }
  fetch() {
    console.log(this._token);
  }
}

const auth = new Auth();
const client = new Client(auth.token);
client.fetch();
auth.updateToken('abc');
client.fetch();

您可以將Auth實例傳遞給Client實例,並通過Auth訪問token 這將確保對Auth._token更新將影響Client

 class Auth { constructor() { this._token = '123'; } get token() { return this._token; } updateToken(newToken) { this._token = newToken; } } class Client { constructor(auth) { this._auth = auth; } fetch() { console.log(this._auth.token); } } const auth = new Auth(); const client = new Client(auth); client.fetch(); auth.updateToken('abc'); client.fetch(); 

設置全局變量將是實現這一目標的一種方法。 然后,您可以簡單地通過Auth更新令牌。

 let token = '' class Auth { constructor() { token = '123'; } get token() { return token; } updateToken(newToken) { token = newToken; } } class Client { fetch() { console.log(token); } } const auth = new Auth(); const client = new Client(); client.fetch(); auth.updateToken('abc'); client.fetch(); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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