Attributes of heirs with prototype do not appear in Javascript reflection

3

I have class Animal which has some properties that are enumerable: true , ie, I can list them via reflection using for..in .

So I have the class Coelho that has the cor attribute. Since rabbit inherits from Animal via prototype , I can call function Descrever() . It turns out that the color of the rabbit is not listed in the reflection.

What am I doing wrong? What is the possible solution?

Code working in JSBin here: link

console.clear();
var Animal = function(nome,comida){
   var _nome=nome||'';
   var _comida=comida||'';
   var self=this;

  Object.defineProperty(this,"Nome",{
                        get:function(){return _nome;},
                        set:function(value){_nome=value;},
                          enumerable:true
                        });


  Object.defineProperty(this,"Comida",{
                        get:function(){return _comida;},
                        set:function(value){_comida=value;},
                          enumerable:true
                        });

this.Descrever=function(){
  for(var prop in self)
    if(typeof self[prop]!=='function')
  console.log(self[prop]);
    };
};

var Coelho = function(cor){
  this.cor=cor||"Branco";

};
Coelho.prototype=new Animal('coelho','legumes');

var a = new Animal("vaca",'grama');
var c = new Coelho('azul');

a.Descrever();
c.Descrever();
    
asked by anonymous 26.11.2014 / 17:26

2 answers

3

I think the problem here is that you are using var self=this; and limiting the reference in the new instance.

If you change the self to this within that for the this will point to the right instance.:

this.Descrever=function(){
  for(var prop in this)
    if(typeof this[prop]!=='function')
  console.log(this[prop]);
    };
}; 

Example: link

p>     
26.11.2014 / 20:57
2

You need to invoke the animal builder in the Rabbit builder.

I have corrected your example (and adapted the function conventions in lower case) here; link

    
26.11.2014 / 19:23