将回调函数传递给原型

Passing a callback function to a prototype

本文关键字:原型 回调 函数      更新时间:2023-09-26

试验一个消息传递模块,该模块将提供在 Node 应用程序中的多个模块之间发出和侦听事件的方法。我的目标是初始化一个侦听器,并让它直接馈送到回调函数中。

在这一点上被语法和JS原型绊倒了。

var events = require('events');
var inter_com = new events.EventEmitter();

var com_bus = {
  initListener:function(listener_name, callback){
    this.listener_name = listener_name;
    this.callback_function = callback;
    inter_com.on(this.listener_name, this.callback_function);
  },
  sendMessage:function(data){
    inter_com.emit(this.listener_name,data);
    console.log('test event sent');
  }
}
var instance_of_com = Object.create(com_bus);
instance_of_com.initListeners('testing',pipeMe);
instance_of_com.sendMessage('its good to be the king');

var pipeMe = function(data){console.log(data)};`

JavaScript 遵循原型继承,

1)要从对象继承,父级需要是一个函数.约定是函数应该命名为InitCap,表示它是一个构造函数。

2)子继承原型,因此您需要从Function_Name.prototype继承,而不是从Function_Name继承。

var events = require('events');
var inter_com = new events.EventEmitter();
function Com_bus() {
}
Com_bus.prototype.initListeners = function(listener_name, callback) {
    this.listener_name = listener_name;
    this.callback_function = callback;
    inter_com.on(this.listener_name, this.callback_function);
};
Com_bus.prototype.sendMessage = function(listener_name, callback) {
    inter_com.emit(this.listener_name, data);
    console.log('test event sent');
};
var pipeMe = function(data) {
    console.log(data)
};
var instance_of_com = Object.create(Com_bus.prototype);
instance_of_com.initListeners('testing', pipeMe);
instance_of_com.sendMessage('its good to be the king');
解决此问题

的一种方法是创建一个返回com_bus实例的工厂:

function returnComBusInstance () {
    // create a closure on these variables
    var listener_name;
    var callback_function;
    return {
        initListener:function(_listener_name, _callback){
            listener_name = _listener_name;
            callback_function = _callback;
            inter_com.on(listener_name, callback_function);
        },
        sendMessage:function(data){
             inter_com.emit(listener_name, data);
             console.log('test event sent');
        }
    }
}

然后:

var com_bus_instance = returnComBusInstance()

我个人尽量避免使用this但如果需要,那么您可以bindcallapply,或者再次创建一个工厂,但在this的上下文中创建闭包

或者您可以将原型属性传递给Object.create

Object.create(com_bus, {
    'listener_name': {value: null, enumerable:true},    
    'callback_function': {value:null, enumerable:true}
});