Jonathan Plumb
Jonathan Plumb

Reputation: 435

How to determine if a property exists on a javascript object

I have created a ton of Image objects in javascript and put them all in an array. However, some of these objects have a mouseover() and mouseout() property, and some do not.

Is there a way to determine if the object I'm referencing has those functions defined or not?

I've tried

if (typeof obj.mouseover !== 'undefined')

but if I never even declared

 mouseover = function() { ... }

on that object, then the code just breaks right there.

So I'm looking for a way to determine if I even added 'var mouseover = function() { ... }' on each object.

Of course, I could go through and make sure EVERY object gets mouseover and mouseout created, even if not set as anything, but that feels like an unnecessary pain if there's another way to just detect if that was set in the first place.

Thanks.

Upvotes: 1

Views: 80

Answers (2)

Joe Chakra
Joe Chakra

Reputation: 56

Use reflection. Eg.: Javascript Reflection

It is then easy to write a function like: DoesMethodExist = function (object_, methodName){...}

that iterates through all the method names of object_ and matches them with methodoName.

Upvotes: -1

Cjmarkham
Cjmarkham

Reputation: 9681

You can check that the method exists on the object via Object.hasOwnProperty('someMethodName')

Mozilla dev link

Upvotes: 7

Related Questions