I’m working on learning Javascript thoroughly, and I’ve run into something that’s bothering me. I thought I’d chuck it out to the community. My question is, why doesn’t the following code work:
var father = {
i: "rudi",
f: function() {
alert(this.i)
}
}
var son = {
prototype:father
}
father.f();
son.f();
When I declare an object literal, I’m surely setting properties for the object. Why can I not set the prototype property here? Is prototype a keyword rather than a property?
Your syntax is wrong. You need to make father the prototype using a constructor, then make an instance of the constructor object like this:
// create father object with property and method
var father= {i:“rudi”, f:function(){ alert(this.i) } }
// create child constructor linking property i to name
function child(name){ this.i=name; }
// make father prototype of child
child.prototype=father;
// create instance of child
var son=new child(“Barry”);
// check if father is really prototype
alert(father.isPrototypeOf(son)) result: true
// use father prototype alert function to show son name
son.f() result: Barry