访问对象返回的值';JavaScript中的s方法

访问对象返回的值';JavaScript中的s方法,javascript,object,methods,properties,Javascript,Object,Methods,Properties,我有一个对象,我想通过它循环并打印出它的所有属性值。我的问题是,当我试图打印出它的一个方法返回的值时,我得到的是该方法的代码,而不是该方法应该返回的值。我肯定我把access语法搞错了,但我想不出来 function Dog (breed,sound) { this.breed = breed; this.sound = sound; this.bark = function(){ alert(this.sound); return th

我有一个对象,我想通过它循环并打印出它的所有属性值。我的问题是,当我试图打印出它的一个方法返回的值时,我得到的是该方法的代码,而不是该方法应该返回的值。我肯定我把access语法搞错了,但我想不出来

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. */
功能犬(品种、声音){
这个品种;
这个声音=声音;
this.bark=函数(){
警惕(这个声音);
返回这个声音;
};
}
var x=新狗(“寻回犬”,“呜呜”);
x、 树皮();//测试:“纬”
for(x中的变量y){
document.getElementById(“结果”).innerHTML+=“
”+x[y]; } /*当y为“bark”时,x[y]返回方法的代码, 但我在寻找价值*/

jshiddle:

您需要这项工作吗?这里的想法也是为了使这种“树皮”属性更通用,这样你就有可能将其用于其他动物

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.
功能犬(品种、声音){
这个品种;
这个声音=声音;
this.noise=警报噪音(this);
}
功能警报噪音(动物){
警惕(动物的声音);
返回动物声音;
}
var x=新狗(“寻回犬”,“呜呜”);
//x、 树皮();/'纬
for(x中的变量y){
document.getElementById(“结果”).innerHTML+=“
”+x[y]; } //当y为'bark'时,x[y]返回属性函数的代码,但我正在查找值。
您喜欢这项工作吗?这里的想法也是为了使这种“树皮”属性更通用,这样你就有可能将其用于其他动物

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.
功能犬(品种、声音){
这个品种;
这个声音=声音;
this.noise=警报噪音(this);
}
功能警报噪音(动物){
警惕(动物的声音);
返回动物声音;
}
var x=新狗(“寻回犬”,“呜呜”);
//x、 树皮();/'纬
for(x中的变量y){
document.getElementById(“结果”).innerHTML+=“
”+x[y]; } //当y为'bark'时,x[y]返回属性函数的代码,但我正在查找值。
因为它是一个函数,你需要在末尾用()调用它,我仍然感到困惑,所以当某些属性是返回值的方法时,无法使用循环遍历该对象的所有属性并打印它们的值?使用这个(x[y]instanceof function?x[y]():x[y]);我用来检测属性是否为函数的方法可能有问题……更好的方法是使用“Object.prototype.toString.call(您的_变量)='[Object function]';”,因为它是一个函数,您需要在末尾用()调用它。我仍然很困惑,因此,当某些属性是返回值的方法时,无法使用循环遍历该对象的所有属性并打印出它们的值?使用此(x[y]instanceof Function?x[y]():x[y]);我用来检测属性是否为函数的方法可能有问题……更好的方法是使用“Object.prototype.toString.call(您的_变量)='[Object function]';”我也不明白你为什么要这样做,但这正是巴克函数在OP的例子中所做的。我也不明白你为什么要这样做,但这正是巴克函数在OP的例子中所做的。