Reputation: 10564
function object1(){
}
object1.prototype.myMethod = function(){};
function object2(){
this.myMethod = function(){};
}
I need to write an if statement that can check if any given object has the myMethod
function, without creating an instance of said object. Is this possible?
This: testMe.prototype.hasOwnProperty('myMethod')
would work only for object1
, but for object2
will return false.
What is this for? I'm trying to emulate interfaces. I need to check if a function respects my interface before working on it and I want to leave the user total freedom on how this function is declared. Creating an instance of that function to check for it's properties sounds like opening a bottle with "water" written on it to check if there is water inside.
Upvotes: 1
Views: 299
Reputation: 10342
There is no way you can check if an object will have some instance methods without instantiating it, because you can add a new method anywhere:
var myObj= {};
...
if (myObj.newMethod) { //false
...
}
myObj.newMethod=function(){...};
if (myObj.newMethod) { //true
...
}
Upvotes: 1
Reputation: 5061
The second one isn't working without instantiating due to assigning this method on instantiating object, only. The code in body of function object2 is its "constructor" and it's run on instantiation only, obviously.
Upvotes: 0