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.

2

2 Answers 2

7

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

Mozilla dev link

Sign up to request clarification or add additional context in comments.

1 Comment

That worked. Thanks!! I was looking everywhere. Guess I was searching for the wrong terms....
-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.