简体   繁体   English

将属性引用从一类传递到另一类

[英]Pass property reference from one class to another

Say I've got 2 classes Auth and Client . 说我有2类AuthClient If I have a property Auth.token I would like to be able to pass that property to Client.token as a reference so that when I change Auth.token it also changes the value of Client.token . 如果我具有Auth.token属性,我希望能够将该属性作为参考传递给Client.token ,这样,当我更改Auth.token它也会更改Client.token的值。

Here's an simplified example that currently doesn't work.. 这是一个目前无法使用的简化示例。

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();

You could pass your Auth instance to your Client instance and access token through Auth . 您可以将Auth实例传递给Client实例,并通过Auth访问token This would ensure that updates to the Auth._token would effect the Client : 这将确保对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(); 

Making a global variable would be one way of achieving this. 设置全局变量将是实现这一目标的一种方法。 You can then simply update the token via the Auth . 然后,您可以简单地通过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