亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

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 關注
  • 121 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號