我想将很多自定义通道逻辑放入它自己的类中。在我的created
生命周期方法中,我正在调用我创建的类中的每个方法,但是如何保留socket
我在 init() 方法中创建的那个实例以用于其他方法?
主程序
import CustomClass from './CustomClass';
created() {
const customClass = new CustomClass();
customClass.init();
customClass.subscribe();
}
自定义类.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');
}
}
您需要将套接字添加为类的属性并使用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');
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句