1

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.

Kingpin2k
  • 47,277
  • 10
  • 78
  • 96
ProllyGeek
  • 15,517
  • 9
  • 53
  • 72

2 Answers2

4

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) {
  ...
}
elclanrs
  • 92,861
  • 21
  • 134
  • 171
1

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"

pwdst
  • 13,909
  • 3
  • 34
  • 50
  • this is a typical answer like elclanrs – ProllyGeek Aug 25 '14 at 20:27
  • 1
    @ProllyGeek I cited elclanrs comment in my answer - but at the time I started writing the answer elclanrs had not posted an answer and you had requested further clarification, which I was attempting to provide. Although we have quoted from the same source, this was not a copy and paste answer. – pwdst Aug 25 '14 at 20:30