Heirs attributes with prototype do not appear in Javascript Reflection

Asked

Viewed 122 times

3

I have the class Animal that has some properties that are enumerable: true, that is, I can list them via Reflection using for..in.

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

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

Code working on Jsbin here: http://jsbin.com/cuyaci/1/edit?js,console,output

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();

2 answers

3


I think the problem here is you’re using var self=this; and limit the reference in the new instance.

If it changes the self for 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]);
    };
}; 

It will already work as you want/should.
Example: http://codepen.io/sergiocrisostomo/pen/myJKJY

2

You need to summon the animal builder in the rabbit builder.

I corrected your example (and adjusted the convection of the functions in minuscule letter) here; http://jsbin.com/dikebekafa/2/edit

  • 1

    I at least am curious for further information :D

  • The explanation is that not only do you need to assign a parent class instance to the prototype of the daughter, but in addition invoke the father builder, which is not invoked automatically. Maybe this post will help more; https://www.exratione.com/2011/05/inheritance-and-initialization-in-nodejs/

Browser other questions tagged

You are not signed in. Login or sign up in order to post.