Type checking is and important and often used feature in scripts, Java Script but also OCL. Each language has its own language for that, this article quickly shows and compares them.
Instanceof
The instanceof operator is available in many languages, so it is in Java script. You can use it to check whether an object is of a dedicated type, either directly or by inheritance. An example:
var fm = ... // assume to get a FailureMode
var foo = fm instanceof Metamodel.safetyModel.Failure; // this will be true
var foo = fm instanceof Metamodel.safetyModel.FailureMode; // this will be true
var foo = fm instanceof Metamodel.safetyModel.Malfunction; // this will be false
In OCL there is the oclIsKIndOf() method with a similar semantic:
-- self assume to get a FailureMode
self.oclIsKIndOf(safetyModel::Failure) -- this will be true
self.oclIsKIndOf(safetyModel::FailureMode) -- this will be true
self.oclIsKIndOf(safetyModel::Malfunction) -- this will be false
Same Type
Sometimes its required to match an exact type and not any base class. In Java script there is in principle no such thing but in medini you can use the prototype (which actually returns the Metaclass):
var fm = ... // assume to get a FailureMode
var foo = fm.prototype == Metamodel.safetyModel.Failure; // this will be false (!)
var foo = fm.prototype == Metamodel.safetyModel.FailureMode; // this will be true
var foo = fm.prototype == Metamodel.safetyModel.Malfunction; // this will be false
OCL has a specific method for that check:
-- self assume to get a FailureMode
self.oclIsTypeOf(safetyModel::Failure) -- this will be false (!)
self.oclIsTypeOf(safetyModel::FailureMode) -- this will be true
self.oclIsTypeOf(safetyModel::Malfunction) -- this will be false
Happy Scripting
Jan
PS: In an earlier version there were a few mistakes in this article, thanks Florent!