简体   繁体   English

如何通过方法传递类实例而不调用构造函数

[英]How to pass a class instance through methods without calling a constructor

I have these two files: 我有这两个文件:

file1.js file1.js

On the first one I call the subscribe method of "Device" passing a class instance called "RemoteControl" 在第一个方法中,我通过一个名为“ RemoteControl”的类实例调用“设备”的订阅方法

import { RemoteControl } from '../lib/devices'
.
.
.
this.device = new Device()
this.device._subscribe('231',RemoteControl)

file2.js file2.js

On this file I have 在这个文件上

export class Device extends Service {
  constructor () {
    super()
    this.valid_devices_list = {uuid: [], deviceClass: {}}
  }

  _discover() {
      this.emit('found', new this.valid_devices_list.deviceClass('231'));
      console.log('Emite')
    }
  }

  _subscribe (uuid , deviceClass) {
    //uuid must be a regex for all bluetooth devices of the same type.
    this.valid_devices_list = {uuid, deviceClass}
    this._discover()
  }

The thing is that when I run this I get the error 事实是,当我运行它时,我得到了错误

this.valid_devices_list.deviceClass is not a constructor this.valid_devices_list.deviceClass不是构造函数

So I don't really know how can I pass the class instance "RemoteControl" to the subscribe instance, then save it on an object and finally use it on the discover method and call the constructor there. 因此,我真的不知道如何将类实例“ RemoteControl”传递给订阅实例,然后将其保存在一个对象上,最后在Discover方法上使用它并在其中调用构造函数。

Any help on this? 有什么帮助吗? Thank you in advance! 先感谢您!

EDIT: 编辑:

devices.js devices.js

export class RemoteControl {
  constructor (uuid) {
    this.uuid = uuid
  }
  _get () {
   //some stuff could be here
  }
}

If RemoteControl is an "instance", then you can do 如果RemoteControl是“实例”,则可以执行

var constructor = this.valid_devices_list.deviceClass.constructor;
this.emit('found', new constructor('231'));

or alternatively you can pass the constructor (depending on the non obvious semantics of your API): 或者,您可以传递构造函数(取决于API的非明显语义):

this.device._subscribe('231', RemoteControl.constructor)

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

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