2

I have an object and I would like to loop through it and print out all the values of its properties. My problem is that when I try to print out the value returned by one of its methods, I get the code of the method instead of the value the method should return. I'm sure I'm making an access syntax typo, but I can't figure it out.

function Dog (breed,sound) {
    this.breed = breed;
    this.sound = sound;
    this.bark = function(){
        alert(this.sound); 
        return this.sound;
    };
}

var x = new Dog("Retriever",'woof');
x.bark(); // Test: 'woof'

for (var y in x) {
    document.getElementById("results").innerHTML +="<br/>"+x[y];
}
/* x[y] when y is 'bark' returns the method's code,
   but I'm looking for the value. */

JSFiddle: http://jsfiddle.net/nysteve/QHumL/4/

4
  • because it's a function and you need to call it with () at the end Commented Oct 3, 2013 at 18:07
  • I'm still confused, so there's no way to loop through all the properties of this object —using a loop —and print out their values when some of the properties are methods that return values? Commented Oct 3, 2013 at 18:10
  • use this (x[y] instanceof Function? x[y]():x[y]); Commented Oct 3, 2013 at 18:12
  • the way I used to detect if a property is function may be problematic...a better way is to use "Object.prototype.toString.call(your_variable) == '[object Function]';" Commented Oct 3, 2013 at 18:23

1 Answer 1

1

Would something like this work for you? The idea here also is to make this "bark" property more generic so you could possibly use this for other animals.

function Dog (breed,sound) {
  this.breed = breed;
  this.sound = sound;
  this.noise = alertNoise(this);
}

function alertNoise(animal) {
    alert(animal.sound); 
    return animal.sound;    
}

var x = new Dog("Retriever",'woof');
//x.bark(); // 'woof'

for (var y in x) {
    document.getElementById("results").innerHTML +="<br/>"+x[y];
}
// x[y] when y is 'bark' returns the property-function's code, but I'm looking for the value.
Sign up to request clarification or add additional context in comments.

1 Comment

I don't understand why you would do this either but it's exactly what the bark function is doing in OP's example.

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.