繁体   English   中英

Vue/JS:在不同的 class 方法中访问相同的变量

[英]Vue/JS: Accessing same variable within different class methods

我想将很多自定义通道逻辑放入它自己的 class 中。 在我created的生命周期方法中,我调用了我创建的 class 中的每个方法,但是如何保留我在 init() 方法中创建的socket实例以用于其他方法?

主.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');
    }

}

您需要将套接字作为属性添加到 class 并使用this关键字访问它

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');
  }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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