简体   繁体   中英

How to pass a class instance through methods without calling a constructor

I have these two files:

file1.js

On the first one I call the subscribe method of "Device" passing a class instance called "RemoteControl"

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

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

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.

Any help on this? Thank you in advance!

EDIT:

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

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):

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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