简体   繁体   中英

Vue/JS: Accessing same variable within different class methods

I want to put a lot of custom channel logic into it's own class. In my created lifecycle method, I am calling each method in the class I created but how can I retain that instance of the socket I created in the init() method for use in the other methods?

Main.vue

import CustomClass from './CustomClass';

created() {

    const customClass = new CustomClass();
    customClass.init();
    customClass.subscribe();
}

CustomClass.js

import Socket from 'Socket';

class CustomClass {

    init() {
        const socket = new Socket(key: XXXXX);
    }
    subscribe() {
       // how to have access to `socket` here that was created in init?
        socket.subscribe(channel: 'xxxx');
    }

}

You need to add the socket as a property on the class and access it using this keyword

import Socket from 'Socket';

class CustomClass {
  
  init() {
      // add the socket as a property on the CustomClass instance
      // it might be worth moving this to a constructor function

      this.socket = new Socket(key: XXXXX);
  }
  subscribe() {
     // access it by using `this` keyword
      this.socket.subscribe(channel: 'xxxx');
  }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM