I am working on implementing a simple Class in JavaScript. I know there are many great libraries out there that already does this. However, my intent is to understand the JavaScript prototype model better. Anyhow, I wrote the following. It is working as far as I can tell but with one catch I will describe later:
function Class(constructor,prototypeObj){
var c = constructor;
c.create = function(){
//var o = new constructor();
var o = Object.create(c.prototype);
c.apply(o,arguments);
return o;
};
c.prototype = prototypeObj;
return c;
}
var Animal = Class(
function Animal(life){
this.life = life;
},
{
type: "animal",
sayLife: function(){
console.log(this.life);
}
}
);
var o = Animal.create(15);
console.log(o instanceof Animal); // True
console.log(o.sayLife()); // 15
console.log(o.type); // "animal"
However, my problem is that when I input in o (for the instance) in the console; it prints
Object {life: 15, type: "animal", sayLife: function}life: 15 __proto__: Object
But I would like it to be
Animal {life: 15, type: "animal", sayLife: function}life: 15 __proto__: Object
If I change line 4 and 5 in the constructor.create method to use new constructor() instead of Object.create(constructor.prototype), I get the desired behaviour but then I have issues passing in arguments to the constructor when initializing a new object. If I return a function other than the constructor passed into the class function, then the objects names would not be Animal but something else like "Object" or "F".
So my question is is there any way to implement the Class function such that the instances of the Class always share the same name as the constructor function?