Can someone explain me why using JavaScript instanceof operator as the side effect to convert its left operand to the type of its right operand.
An RDF example:
// rsc is an object of type nsIRDFNode
rsc instanceof Components.interfaces.nsIRDFLiteral;
// now resource can be used as an is an object of type nsIRDFLiteral // same as // rsc = rsc.QueryInterface(Components.interfaces.nsIRDFLiteral);
Is this shortcut safe?
Yes, this is by design. XPConnect has worked this way for over 2 years and I'm sure it is not going to change. This is part of what is called 'interface flattening'. XPConnect will make the JSObject representing the underlying object reflect all of the scriptable methods and properties of all interfaces that XPConnect is *aware* that object supports. In both of these cases your code is telling XPConnect to verify that the object supports the interface. So, it does not matter which of various ways are used to inform XPConnect that the given object supports a given interface - the result is the same.
The most common form is...
b = a.QueryInterface(Components.interfaces.nsIFoo);
...because this is backward compatible with how XPConnect originally worked (and what people are used to doing in C++ code) and lots of people are used to doing this. But, you could actually leave off the "b = " part because the above will result in 'a' and 'b' referring to the same object anyway.
'instanceof' is not really a shortcut, it is just another way of producing the same state. The one important difference between 'instanceof' and 'QueryInterface' in this context is that 'instanceof' will simply return true or false. But, 'QueryInterface' will actually throw a JavaScript exception if the underlying object does not support the given interface.
John.
