2013-10-03 36 views
0

我有一個對象,我想循環它並打印出其屬性的所有值。我的問題是,當我嘗試打印出其方法返回的值時,我得到了該方法的代碼,而不是方法返回的值。我確定我正在編寫訪問語法錯字,但我無法弄清楚。在JavaScript中訪問對象方法返回的值

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/

+0

因爲它是一個功能,你需要調用它()在結束 –

+0

我仍然困惑,所以通過這個對象的所有屬性 - 使用一個循環 - 和打印出來有沒有辦法來循環當一些屬性是返回值的方法時,它們的值? – brooklynsweb

+0

使用this(x [y] instanceof Function?x [y]():x [y]); –

回答

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. 
+0

但這隻能調用一個函數來獲取它自己的聲音... –

+1

我不明白你爲什麼要這樣做,但它正是OP的例子中樹皮函數的作用。 – Ant