为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

慕侠2389804 2022-11-27 16:11:35
我想将大量自定义频道逻辑放入它自己的类中。在我的created生命周期方法中,我正在调用我创建的类中的每个方法,但是我如何保留socket我在 init() 方法中创建的实例以供其他方法使用?主视图import CustomClass from './CustomClass';created() {    const customClass = new CustomClass();    customClass.init();    customClass.subscribe();}自定义类.jsimport 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');    }}
查看完整描述

1 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

您需要将套接字添加为类的属性并使用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');

  }


}


查看完整回答
反对 回复 2022-11-27
  • 1 回答
  • 0 关注
  • 78 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信