Javascript: prototypeal inheritance and the prototype proprity
Posted
by JanD
on Stack Overflow
See other posts from Stack Overflow
or by JanD
Published on 2010-03-14T01:30:37Z
Indexed on
2010/03/14
1:35 UTC
Read the original article
Hit count: 383
JavaScript
|inheritance
Hi,
I have a simple code fragment in JS working with prototype inheritance.
function object(o) {
function F() {}
F.prototype = o;
return new F();
}
//the following code block has a alternate version
var mammal={
color: "brown",
getColor: function(){
return this.color;
}
}
var myCat = object(mammal);
myCat.meow = function(){return "meow";}
that worked fine but adding this:
mammal.prototype.kindOf = "predator";
does not. ("mammal.prototype is undefined")
Since I guessed that object maybe have no prototype I rewrote it, replacing the var mammal={... block with:
function mammal(){
this.color="brown";
this.getColor = function(){return this.color;}
}
which gave me a bunch of other errors:
"Function.prototype.toString called on incompatible object"
and if I try to call _myCat.getColor()
"myCat.getColor is not a function"
Now I am totally confused. After reading Crockford, and Flanagan I did not get the solution for the errors. So it would be great if somebody knows...
- why is the prototype undefined in the first example (which is foremost concern; I thought the prototype of explicitly set in the object() function)
- why get I these strange errors trying to use the mammal function as prototype object in the object() function?
© Stack Overflow or respective owner