Best practices for callbacks within a scope

馋奶兔 提交于 2019-12-08 05:33:55

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/17032098/best-practices-for-callbacks-within-a-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!