I am trying to learn different object declaration type and inheritance. Here, first I declared an object named parent
using an object constructor. Then, another object child
is introduced which inherits all the properties from parent
.
Parent object using constructor is:
function parent(){
this.parent_last_name="khan";
this.occupation="business";
}
Then a child object is declared and I make it inherit all the properties and methods from parent object using
child.prototype=new parent();
In the same example, I replaced the constructor type declaration and used object literal type declaration.
var parent={
name: "khan",
occupation: "business",
ask: function(){
alert("what do you do?");
},
};
It is giving me an error that "parent is not a constructor".and it is not printing anything.
My question is : 1) Why is the object literal is not working with this particular example? When do I use object literal type and when do I use a constructor?
2)advantage of constructor over object literal
and 3)literal type object declaration can do what i want to do here?
WHOLE CODE
<html>
<body>
<script>
function parent() {
this.parent_last_name = "khan";
this.occupation = "business";
}
parent.prototype.ask = function() {
alert("what do you do?");
}
function child() {
this.child_name = "mohsin";
this.occupation = "student";
}
child.prototype = new parent();
var lol = new child();
document.write(lol.child_name + " " + lol.parent_last_name);
</script>
</body>
</html>
Browser: Firefox