1

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.

Jonathan Plumb
  • 417
  • 1
  • 4
  • 12

2 Answers2

7

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

Mozilla dev link

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
-1

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.

Community
  • 1
  • 1
Joe Chakra
  • 56
  • 3