Are certain node objects inheriting from two classes? - javascript

In node guide, it says that:
"The request object that's passed in to a handler implements the
ReadableStream interface."
However, afterwards it also says that
"Note: The request object is an instance of IncomingMessage.".
So how is request also instance of IncomingMessage and also it implements RedableStream interface?
How would you achieve that in JS?
Also, I thought in JS there were no interfaces?

If you look at the node.js source for an http incoming message, you see this:
/* Abstract base class for ServerRequest and ClientResponse. */
function IncomingMessage(socket) {
Stream.Readable.call(this);
....
}
and this:
util.inherits(IncomingMessage, Stream.Readable);
Which shows that an IncomingMessage constructor inherits from a Stream.Readable. It also overrides some of the readable methods to modify their behavior.
How would you achieve that in JS?
You would create your own object that inherits from another.

An object can both "implement" and "be an instance of" something, but the interface is just for documentation purposes.
In JS, to be an instance of something means that obj instanceof Something is true.
In dynamic languages, like JavaScript, to implement an interface means the object is expected to have certain methods. This is commonly known as duck-typing.
If an IncommingMessage behaves like a ReadableStream, and can be used as a ReadableStream, then it must be a ReadableStream.

Related

How to instantiate a <code></code> element in JavaScript (NodeJS)?

The HTMLPreElement type in JavaScript produces a DOM element corresponding to the <pre> tag. Where is the type corresponding to <code>? It seems there should be an HTMLCodeElement type, but there isn't. How do I go about instantiating this in NodeJS JavaScript?
const c0d3 = document.createElement("code");
Object.getPrototypeOf(c0d3).constructor.toString();
//function(){return a.Reflect.construct(a.HTMLElement,[],this.constructor)}
At least on the browser side (Chrome, on node side you possibly have other workarounds to create mock DOM elements), it is not directly a distinct constructor, but rather a wrapper function that makes use of HTMLElement itself and another function this.constructor that is passed as an argument to Reflect.construct.
The old way of creating these native constructors are generally something like:
//Instances inherit from parent proto
HTMLSomeChildElementFunc.prototype = Object.create(HTMLSomeParentElementFunc.prototype);
//Statics are inherited on the constructor
Object.setPrototypeOf(HTMLSomeCHildElement, HTMLSomeParentElement);
In this case it is a bit different, they went for some sort of monkey patch.

Why do some array methods rely on the global Array object?

I'm going through the MDN docs on arrays and when we want to test whether or not an object is an array we use isArray(). However, it's usage is very different to most of the other methods. When you use the regular syntax an error pops up:
console.log([1,2,3].isArray()); // TypeError: [1, 2, 3].isArray is not a function
Whereas this does work:
console.log(Array.isArray([1,2,3]))
I don't understand why isArray() (and a couple of other methods) rely upon some global object rather than just being accessible via the object in question. Why do some methods require the global array object?
rather than just being accessible via the object in question.
Because the whole purpose of Array.isArray is to be called on unknown objects. You don't know whether it's an array, you wouldn't know whether the method was accessible on it. The static method even works with values like null, which would inevitably throw an exception when you tried to invoke a method on them.
Digression:
isArray being callable as an instance method can work. In languages where everything is an object, like Smalltalk, Ruby or Io, even things like nil can have a isNil method. This approach has other problems of course, as with dynamic method dispatch every arbitrary object could overwrite the method and claim to be an array - on the other hand, that's exactly what we want for duck typing.
We could even simulate this in JS using Object.prototype.isArray = () => false; and Array.prototype.isArray = () => true;. Apart from failing on null and undefined, it still wouldn't work with objects that don't inherit from (our realm's) Object.prototype. And JavaScript "properties" that mix data fields and methods don't help either (consider the object parsed from the JSON string {"isArray":"maybe"}). We would always have to expect an exception from either .isArray not being a function, or from it being overwritten with a method that throws.
If we want to go for duck typing in JS, checking whether an object has an integer .length property is usually the way to go. Or more advanced, trying to follow the symbol-based iteration protocol. (That's what Array.from uses, for example).
But since arrays are a bit special in JS (with their magic .length property), we want a built-in reliable way to detect them, and that's what Array.isArray does.
Regarding other static Array methods: Array.of is pretty obvious, it's a factory function (like a constructor) and it can't be an instance method because there is no instance to work with in the first place. For Array.from the situation is a bit more like with isArray, a duck-typing Object.prototype.toArray approach could have worked as well but was dismissed for practical and design reasons.
See also Why were ES5 Object methods not added to Object.prototype?, Why use Object.prototype.hasOwnProperty.call(myObj, prop) instead of myObj.hasOwnProperty(prop)? and Why is it Object.defineProperty() rather than this.defineProperty() (for objects)? for similar discussions.
.isArray() is a static method, it exists on the Array "class" but not on each particular instance. Static methods are called like this: Array.isArray(). Object.create() is another example.
Methods like .map or .slice are not static, so they exist on each instance of the Array "class".
Array (denoted with a captial "A") indicates the JavaScript native Array object. [...] represents an instance of an array. As with many languages, some properties/methods are static. That is, they don't exist on instances only the type. This is often done when the value of the property or behavior of the method doesn't vary from instance to instance, so there's no need for it to be "instance-specific". Figuring out if something is an array, doesn't change from instance to instance (and frankly, doesn't make a lot of sense to ask an array instance if it is an instance of an Array).

How to show an object provided as an argument by a user on a UML class diagram?

I have a JavaScript function, which is supposed to act like a class, and it needs several pieces of data from a user.
I decided to make it to expect one single object with those data pieces as its arguments, like:
new ClassFunction({
arg_1: 'foo',
arg_2: 'bar'
});
What is the best way to show this on a UML class diagram?
Should I write it as a comment in the curly braces or as a separate note or as an abstract class with a dependency line from the constructor class (ClassFunction) to that abstract class?
Or may be something else?
JavaScript function, which is supposed to act like a class
The more proper term would be object constructor; this may also give you a better idea of what you are actually trying to do.
Now the parameter provided to the constructor is some anonymous class that understands arg_1 and arg_2. UML models this via DataTypes, denoted with the <<dataType>> keyword.
A DataType is a kind of Classifier. DataType differs from Class in that instances of a DataType are identified only by their value. All instances of a DataType with the same value are considered to be equal instances. [UML Spec 10.2]
So for example your case could be modeled as the following:

Deep clone in GWT

While going through this link
How to Deep clone in javascript
I came across a generic clone method (In the accepted answer) . I tried it out running directly in javascript and it runs giving perfect outputs.
I put that code in the native tag and am trying to clone an object in GWT.
My class which am trying to clone is
private class Container
{
Integer i = 5;
}
and when I try to do that, its just returning me the same object. Could anyone please help?
Ask me anything if its not clear. Thanks a ton.
Jonathan is right: the way (and the only one in GWT) is to use https://code.google.com/p/google-web-toolkit/wiki/AutoBean
This may seam awkward but it works perfectly since many concepts are related to that (EntityProxy in RequestFactory relies also on that mechanism, and it's the future of GWT).
Deep json persistence also works with auto beans.
The only thing you have to do is to create an interface that describes your class (and implement it in your class):
public interface ContainerBean {
Integer getI();
void setI(Integer i);
}
Then create your factory interface
interface MyFactory extends AutoBeanFactory {
// Factory method for a simple AutoBean
AutoBean<ContainerBean> container();
// Factory method for a non-simple type or to wrap an existing instance
AutoBean<ContainerBean> container(ContainerBean toWrap);
}
Now you can wrap your object and clone it (through json since)
clone()
An AutoBean and the property values stored within it can be cloned.
The clone() method has a boolean parameter that will trigger a deep or
a shallow copy. Any tag values associated with the AutoBean will not
be cloned. AutoBeans that wrap a delegate object cannot be cloned.
https://code.google.com/p/google-web-toolkit/wiki/AutoBean#clone()
therefore use this method instead:
https://code.google.com/p/google-web-toolkit/wiki/AutoBean#AutoBeanCodex
One way you could possibly achieve this is with AutoBeans.
I think the only trick with this method is that you'll have to use an AutoBeanFactory to create all of your classes.
Then, you could encode your autobean into a Splittable, then use the result to decode into a new autobean instance.

What is the purpose of an abstract METHOD in javascript?

// A convenient function that can be used for any abstract method
function abstractmethod() { throw new Error("abstract method"); }
// The AbstractSet class defines a single abstract method, contains().
function AbstractSet() { throw new Error("Can't instantiate abstract classes");}
AbstractSet.prototype.contains = abstractmethod;
From "Javascript: The Definitive Guide - 9.7.4 Class Hierarchies and Abstract Classes"
I understand the utility of abstract classes in JavaScript. What I don't understand is the necessity or use of setting abstract methods that only throw an error. You can't create an instance of that class, so only instances of the subclasses will exist. They'll each have their own definition for these methods, so why establish an inheritance to a method that just throws a generic error?
Thank you in advance for your guiding response.
I assume that the purpose of this is that it's not a generic error - it's an error that informs you where you went wrong (i.e. you failed to override the method in a subclass). If you didn't define that method, you would get an error saying "Undefined is not a function" (or something similar) and you'd have to spend time hunting around your code to understand why - this way it fails in a more verbose and useful manner.
The other reason, I'd assume, is to indicate the class interface to downstream developers implementing subclasses. Javascript doesn't have any kind of formal interface declaration, so it's helpful to be able to inspect the abstract class and see what methods I'm expected to implement.

Categories

Resources