1

我有一个对象,我想遍历它并打印出它的所有属性值。我的问题是,当我尝试打印其方法之一返回的值时,我得到的是方法的代码,而不是方法应该返回的值。我确定我正在制作访问语法错字,但我无法弄清楚。

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

1 回答 1

1

像这样的东西对你有用吗?这里的想法也是让这个“树皮”属性更通用,这样你就可以将它用于其他动物。

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.
于 2013-10-03T18:19:33.823 回答