簡體   English   中英

如何通過方法傳遞類實例而不調用構造函數

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

我有這兩個文件:

file1.js

在第一個方法中,我通過一個名為“ RemoteControl”的類實例調用“設備”的訂閱方法

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

file2.js

在這個文件上

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()
  }

事實是,當我運行它時,我得到了錯誤

this.valid_devices_list.deviceClass不是構造函數

因此,我真的不知道如何將類實例“ RemoteControl”傳遞給訂閱實例,然后將其保存在一個對象上,最后在Discover方法上使用它並在其中調用構造函數。

有什么幫助嗎? 先感謝您!

編輯:

devices.js

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

如果RemoteControl是“實例”,則可以執行

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

或者,您可以傳遞構造函數(取決於API的非明顯語義):

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM