1

I've tried the following code and was surprised to discover that for var in object returns also objects methods. I'm not sure why does it happen, are object methods essentially properties? Is there any way to make it return only properties containing values?

var object = {p1: 1, p2: 2, p3: 3};

    object.funkcja = function() {
        for (var x in object) {document.getElementById("test").innerHTML += object[x] + "<BR>";}
    };

example:

Łukasz
  • 453
  • 1
  • 5
  • 13

4 Answers4

0

Checking like bellow should work.

for (var x in object) {
    if(object.hasOwnProperty(x)){
        document.getElementById("test").innerHTML += object[x] + "<BR>";
    }

}
Mritunjay
  • 25,338
  • 7
  • 55
  • 68
0

It's because JavaScript doesn't make difference between values and methods. You'll have to filter the methods from the values yourself. I suggest you use in your loop this function found here: How can I check if a javascript variable is function type?

for (var p in object){
    if(isFunctionA(p) == false){
        //Make your work on props here.
    }
}
function isFunctionA(object) {
 return object && getClass.call(object) == '[object Function]';
}
Community
  • 1
  • 1
317
  • 67
  • 5
0

Yes, the methods of an object are simply properties which happen to be functions. You can test whether or not a property is a function using

 if(typeof object[x] === 'function')

or

 if(object[x] instanceof Function)

I believe the instanceof operator is slightly more efficient, but it can fail to work if you have multiple global contexts in effect (e.g. if you are passing objects between different frames).

It's also worth noting that the for in loop will return properties defined on the object's prototype as well as its instance properties. To avoid this, you can use

 if(object.hasOwnProperty(x))
Ben Griffiths
  • 1,676
  • 15
  • 13
0

I think this is the right way:

for (var x in object) {
    if(object.hasOwnProperty(x) && !(object[x] instanceof Function) ){
        document.getElementById("test").innerHTML += object[x] + "<BR>";
    }
}
user2883814
  • 365
  • 2
  • 18