Object creation - Literal or Constructor?
Hi all
I’m work on object creation and inhertiance and I’m trying to work out the best pattern.
I can create an object Literal like this
/*--- Obj-1 ---*/
var Animal_1 = {};
Animal_1.name = 'chris';
Animal_1.getName = function(){
alert('Name is ' + this.name);
}
Animal_1.getName();
and I can create the same type of obejct with a constructor function
/*--- Obj-2 --*/
function Animal_2(name){
this.name = name
}
Animal_2.prototype.getName = function(){
alert('Name is ' + this.name);
}
var tom = new Animal_2('tom');
tom.getName();
My first question is are these two approaches creating the same object. The conctructor approach uses the prototype to create the method. The object Literal approach doesn’t reference the prototype at all. I thought that methods should be placed in the prototype.
Inhertiance
Using the Constructor approach I can create another object that inhertrits from Obj-2
/*--- Obj-3 --*/
function Animal_3(name, mood){
Animal_2.call(this)
this.name = name,
this.mood = mood
}
Animal_3.prototype = new Animal_2();
Animal_3.prototype.constructor = Animal_3;
var john = new Animal_3('john', 'happy');
john.getName();
alert(john.mood)
How would I create another object that inhertrits using the object Literal approach.