Kindly explain Constructors & methods in detail.I am getting confused between the two?


#1

function Rabbit(adjective) {
this.adjective = adjective;
this.describeMyself = function() {
console.log("I am a " + this.adjective + " rabbit");
};
}

// now we can easily make all of our rabbits
var rabbit1 = new Rabbit("fluffy");
var rabbit2 = new Rabbit("happy");
var rabbit3 = new Rabbit("sleepy");
rabbit1.describeMyself();
rabbit2.describeMyself();
rabbit3.describeMyself();


#2

Constructors initialize your object, and methods (or functions) are the actions that your object can do.


#3

thanks for the explanation


#4

Welcome! :slightly_smiling:


#5

Hey could you please explain what is wrong with this code.Iam getting an error:

// Our Person constructor
function Person(name, age) {
this.name;
this.age;
};
var family = new Array();
family[0] = new Person("alice", 40);
family[1] = new Person("bob", 42);
family[2] = new Person("michelle", 8);
family[3] = new Person("timmy", 6);

for (var i = 0; i < family.length; i++) {
console.log(family[i].name);
};

ERROR: It looks like your Person constructor does not properly save the first argument as the person's name


#6

You assign it like this:

function hi(arg) {
    this.arg = arg;
}

#7

hey thanks a lot for the explaination :slightly_smiling: