简体   繁体   中英

Best practices for callbacks within a scope

Typically, in "constructor" you subscribe to events with lambda-functions:

function Something(){
   this.on('message', function(){ ... });
}
util.inherits(Something, events.EventEmitter);

This works well but extends bad. Methods play better with inheritance:

function Something(){
   this.on('message', this._onMessage);
}
util.inherits(Something, events.EventEmitter);

Something.prototype._onMessage = function(){ ... };

What are the best practices to keep these event handler functions?

if i understood the question correctly then i think that it depends on how much open for changes you are willing to be.

your second example opens the option for subclasses (or, actually, any class) to override the handler's code, which isn't necessarily a good thing.

the first example prevents overriding but at the cost of having anonymous functions (sometimes containing a lot of code) inside your constructor. however, this code can be extracted to another private function (not on the prototype, just a regular function inside the module's file).

the open-close principal deals with this kind of questions.

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