Weird inheritance in Node.js - node.js

I've been poking into some Node.js modules in the hopes of learning something I could have missed while creating a module with similar functionality. Then I came across this code from Hound:
function Hound() {
//why this?
events.EventEmitter.call(this)
}
//ok, so inheriting the EventEmitter
util.inherits(Hound, events.EventEmitter);
I know that the util.inherits() function from Node.js creates a new Parent instance as the prototype of the child constructor as stated in the docs:
The prototype of constructor will be set to a new object created from superConstructor.
So if our constructor is inheriting EventEmitter through util.inherits(), what is that code in the constructor for?

It's just making your Hound class an EventEmitter object.
It gives your the EventEmitter instance methods to the class.
E.g., houndInstance.emit('something')
Other objects that are listening to these events can then respond to them.
Per your comment:
// constructor
function Hound() {
// equivalent of calling a "super" or "parent" constructor
SomeClass.call(this);
}
In JavaScript, .call(context) is a means of invoking a function in a specific context. In the example above, we're just calling the SomeClass constructor and passing this (the Hound class in this example) as the context.

From your comments:
But doesn't util.inherits() already cover that? Or am I missing something?
What you are missing is that util.inherits() merely inherits the parent object. It doesn't set up the constructor to automatically call the parent object's constructor. In most cases it would be enough since most objects don't do much initialization in their constructors.
But events.EventEmitter apparently does some initialization in the constructor that has some important side effects. Since prototypical inheritance does not automatically call the parent's constructor you need to call it manually in this case. Hence the events.EventEmitter.call(this) line.
Note that an alternative is to use the module pattern which always calls the parent's constructor. That is because the module pattern is not inheritance per-se but emulates inheritance by abusing the mixin/decorator pattern - it creates an object from the parent constructor and manually add attributes to it. Lots of people don't like the module pattern because it duplicates functions and attrubutes - hence they see it as wasting memory. Also, it's not proper inheritance and so breaks stuff like instanceof.

Related

Overriding a function still calls parent class before child method

I am new to Haxe and only plans to deploy for the web.
So I have a class A which has a method name doThis(). On class B, I inherited class A. I override doThis() on class B. When I check on the debugger, class A doThis() is being called and then class B doThis() is called as well.
My intuition is, I have overridden the methods explicitly and the only way I can call the parent is via a super.doThis() but it seems it does this automatically. I only want the version of doThis() to be B. Not A's.
Any thought on why it behaves like this? I think I a missing something here.
Thanks!
Without any further information, I'd bet good money that you have your debugger breakpoints on the definition of doThis, when you meant to put them in the invocation of doThis (inside the function body).
Other possible (but less likely) reasons:
A macro function is inserting a super.doThis() call
A modified Haxe compiler or JS generator is emitting a super.doThis() call.
Unless the function you are overriding is the constructor function new, calling the parent (super) function is optional. Furthermore, you can stipulate when the parent function is called by adjusting when you call super.doThis().
To illustrate, here is code that only runs the child classes function on try.haxe. It sounds like you may have already tried a similar approach, so ensure that you aren't missing some code that you may not be aware is calling the super function.
I think you're doing the right thing.
perhaps add some println to the parent function and the child function to make sure what you describe is what actually happens.
In other words, the debugger is not just playing with you.

Inheritance and the constructor chain with native duktape/C functions

Using native functions to implement a class constructor is described in the duktape wiki. What's left out there however is how to implement a class hierarchy.
When your native constructor is called for a derived class, how do you handle the inheritance chain in duktape? In Javascript you would usually do something like:
function Base(){
}
...
function SubClass(){
// Call super constructor.
Base.call(this);
}
How would you implement that in duktape? We cannot use duk_call() since we don't have a method to call.
If you just want the same behavior as in the Ecmascript example, you would do something like:
duk_get_global_string(ctx, "Base");
duk_push_this(ctx);
duk_call_method(ctx, 0); /* = Base.call(this) */

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.

solving multiple inheritance (for precooked classes)

What I need: a class with two parents, which are ContextBoundObject and another class.
Why: I need to access the ContextBoundOject to log the method calls.
Composition works? As of now, no (types are not recognized, among other things).
Are other ways to do this? Yes, but not so automatable and without third-party components (maybe a T4 could do, but I'm no expert).
A more detailed explanation.
I need to extend System classes (some of which have already MarshalByRefObject (which is the parent of ContextBoundObject) for parent, for example ServiceBase and FileSystemWatcher, and some not, for example Exception and Timer) to access some inner workings of the framework, so I can log method calls (for now; in future it may change).
If I use this way I only have to add a class name to the object I want to log, instead of adding the logging calls to every method, but obviously I can't do this:
public class MyService:ServiceBase,ContextBoundObject,IDisposable{
public MyService(){}
public Dispose(){}
}
so one could try the usual solution, interfaces, but then if I call Run as in:
ServiceBase.Run(new MyService());
using a hypotethical interface IServiceBase it wouldn't work, because the type ServiceBase is not castable to IServiceBase -- it doesn't inherit from any interface. The problem is even worse with exceptions: throw only accepts a type descending from Exception.
The reverse, producing a IContextBoundObject interface, doesn't seem to work either: the logging mechanism doesn't work by methods, so I don't need to implement any, just an attribute and some small internal classes (and inheriting from ContextBoundObject, not even from MarshalByRefObject, which the metadata present as practically the same).
From what I see, extending from ContextBoundObject puts the extended class in a Proxy (probably because in this way the method calls use SyncProcessMessage(IMessage) and so can be intercepted and logged), maybe there's a way to do it without inheritance, or maybe there could be pre or post compiling techniques available for surrounding methods with logging calls (like T4 Text Templates), I don't know.
If someone wants to give this a look, I used a customized version of MSTestExtentions in my program to do the logging (of the method calls).
Any ideas are appreciated. There could be the need for more explanations, just ask.
Logging method calls is usually done using attributes to annotate classes or methods for which you want to have logging enabled. This is called Aspect Oriented Programming.
For this to work, you need a software that understands those attributes and post-processes your assembly by adding the necessary code to the methods / classes that have been annotated.
For C# there exists PostSharp. See here for an introduction.
Experimenting with proxies I found a way that apparently logs explicit calls.
Essentially I create a RealProxy like in example in the msdn, then obtain the TransparentProxy and use that as the normal object.
The logging is done in the Invoke method overridden in the customized RealProxy class.
static void Main(){
...
var ServiceClassProxy=new ServiceRealProxy(typeof(AServiceBaseClass),new object[]{/*args*/});
aServiceInstance=(AServiceBaseClass)ServiceClassProxy.GetTransparentProxy();
ServiceBase.Run(aServiceInstance);
...
}
In the proxy class the Invoke will be done like this:
class ServiceRealProxy:RealProxy{
...
[SecurityPermissionAttribute(SecurityAction.LinkDemand, Flags=SecurityPermissionFlag.Infrastructure)]
public override IMessage Invoke(IMessage myIMessage){
// remember to set the "__Uri" property you get in the constructor
...
/* logging before */
myReturnMessage = ChannelServices.SyncDispatchMessage(myIMessage);
/* logging after */
...
return myReturnMessage;
// it could be useful making a switch for all the derived types from IMessage; I see 18 of them, from
// System.Runtime.Remoting.Messaging.ConstructionCall
// ... to
// System.Runtime.Remoting.Messaging.TransitionCall
}
...
}
I have still to investigate extensively, but the logging happened. This isn't an answer to my original problem because I have still to test this on classes that don't inherit from MarshalByRefObject.

Kohana helper attribute

I have a question that keeps bothering me. Currently, I have started using Kohana 3.2 Framework. I've written a helper to handle some functionality - I have a number of methods, which are (as it should be) declared STATIC. But, all of these methods are somehow working with the database, so I need to load a model. Currently, every method has a non-static variable like this:
$comment = new Model_Comments;
$comment->addComment("abc");
OK, it seems to be working, but then I wanted to get rid of this redundancy by using class attribute to hold the instance of the model (with is class as well).
Something like this:
private static $comment; // Declaring attribute
self::$comment = new Model_Comment; // This is done within helper __constuct method
self::$comment->addComment("abc"); // And call it within the method.
But, I got failed with: Call to a member function addComment() on a non-object
Question is: is it possible to do it ? Maybe there are some other approaches ?
Sorry for a long story and, thanks in advice! :P
A static method cannot call a non-static method without operating on an instance of the class. So, what you're proposing won't work. There may be a way do accomplish something similar, but what about trying the following:
You could implement the singleton or factory pattern for your "helper" class. Then, you could create the model (as an attribute) as you instantiate/return the instance. With an actual instance of your "helper" class, you won't have to worry about the static scope issues.
In other words, you can create a helper-like class as a "normal" class in your application that, upon creation, always has the necessary model available.
I'd be happy to help further if this approach makes sense.
David

Resources