Reputation: 9066
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
Upvotes: 0
Views: 88
Reputation: 64943
An object literal is just an instance of Object
while a constructor function is an instance of Function
which can become a constructor when new
operator is used behind it (i.e. new SomeFunc()
).
Remember that functions are JavaScript's first-citizen constructs. They can be either old-school procedural functions, object methods and also object constructors.
When to use object constructors? Easy: when you want to reuse the same object structure across same or other script files and you might need prototype chain (inheritance).
If you need an object to be passed as argument of some function call or something like that, object literals is the way to go.
Anyway, whenever you create a function (either constructor function or not), you've a prototype available to define members that will be part of any instance created with the whole function. Since ECMA-Script 5.x you can also use Object.create(...)
:
var A = function() {};
A.prototype.doX = function();
Object.create(A.prototype, {
doY: {
value: function() { }
}
});
Object.create
approach is also another way to get inheritance in JavaScript, since it creates an object where its prototype is the one provided as first parameter of the whole function.
You can't use an object literal using new
operator and this is why Web browsers (or ECMA-Script runtimes...) will throw an error, because an object literal is an instance of Object
rather than being of Function
.
Upvotes: 3