It's a bad idea to use the .constructor property for what you're trying to do because that eliminates any essence of subclassing and eliminates the ability for the caller to use their own flavor of observable that supports the required contract, but isn't named what you are looking for. It also removes the ability to use mixins or composite objects where the original constructor isn't the observable itself. These are likely not things you want to prohibit.
Now that you've modified the question to show what you're really trying to do (detect if you're being passed an observable object), you have a couple choices:
- Test
instanceof to see if it derives from a known base object.
- Test the object to see if it has the known and expected properties of an object that behaves the way you want. This is called "duck" typing. If it quacks like a duck, it must be a duck and is enough of a duck for what you're trying to do even though you haven't checked its DNA.
I'd suggest you extend what you had with this:
return (val &&
typeof val.subscribe === 'function' &&
typeof val.unsubscribe === 'function')
to add a couple more properties/methods that you expect to be on a legitimate observable object. You can make the test as stringent as you want (test for 10 separate methods if you want or even call a couple methods with no side effects to see if they return the desired value), but in reality, you probably just want to make sure that it somewhat smells like it's an observable and then if the caller is giving you a half baked observable, that's kind of their issue. Chance are your real goal here is to just advise the developer when they've made a programming mistake so you can "early on" throw an exception during their development that shows they've passed in the wrong kind of object. The simplest type of smell test should suffice for that. You generally aren't interested in testing for subleties.
There's really no reason to test for more properties than you're actually going to use. If someone wants to make their own version of an observable that supports the properties you use, then they should be allowed to do that so you shouldn't have to worry beyond that. If they try to use something that looks like an observable, but doesn't quite implement the right interfaces on the object, then that's kind of on them for not giving you a legit observable, not really on your API.
.constructorproperty, then we can more fully advise if that's an appropriate use of the property.instanceofto see if it inherits from some known base object or test for the existence of certain properties that indicates it has the appropriate methods to be an observable? A subclassed object won't have a known.constructoras the constructor will point to the subclassed object's constructor.