Reputation: 15836
for example i have an array , lets call it myArray
where :
var myArray = ['foo', 'bar'];
even though , myArray.join()
will return 'foo,bar'
, the check myArray.hasOwnProperty('join')
, will return false
, because simply hasOwnProperty()
will not traverse the prototype chain.
Is there a way to do same function with ability to traverse the prototype chain?
P.S : even a custom method will do.
Upvotes: 1
Views: 223
Reputation: 13735
If you want to determine if a method or property is available within either the object or within the prototype chain for the object you can use the in operator as cited by elclanrs.
The in operator returns true for properties in the prototype chain.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
In your example you could write-
if ('join' in myArray) { // do something }
If you want to determine the type of a property within the prototype chain then you can also use the typeof operator. I can't find a "plain English" citation that this works with prototype operators, but if you type the following in the console of the dev tools of your choice-
var myArray = ['foo', 'bar']; typeof(myArray.join);
This will return "function" as expected, demonstrating that this operator does function with prototype functions and properties - and this is something I can also attest to from my experience. The typeof operator will return one of-
"undefined", "object", "boolean", "number", "string"
Upvotes: 1
Reputation: 94101
You can use the in
operator.
The in operator returns true for properties in the prototype chain.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in
Like:
if ('join' in myArray) {
...
}
Upvotes: 4