Let's say I have a class named Human.
function Human(name, gender, age, personality){
this.name = name;
this.gender = gender;
this.age = age;
this.personality = personality;
}
and I have some functions for the class such as greeting and introduce. So I create them like this:
Human.prototype.introduce = function() {
var _gender = {"M": "Boy", "F": "Girl"};
switch(this.personality)
{
case "passionate":
alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
break;
case "aggressive":
alert("I'm " + this.name + ". What you want? ");
break;
}
}
Human.prototype.greeting = function() {
alert("Hi!");
}
Since introduce and greeting can be grouped by the same category (let's name it speak), how can I simply wrap this two functions with an object? I've tried this:
Human.prototype.speak = {};
Human.prototype.speak.greeting = function(){
alert("Hi!");
}
Human.prototype.speak.introduce = function(){
var _gender = {"M": "Boy", "F": "Girl"};
switch(this.personality)
{
case "passionate":
alert("Hi, how are you? My name is " + this.name + ". I'm " + this.age + " years old " + _gender[this.gender] + ". ");
break;
case "aggressive":
alert("I'm " + this.name + ". What you want? ");
break;
}
}
Now the question is, when a function is wrapped by an object, this in the introduce function is no longer referring to the instance. So how can I work this out?
I would like to call the function as this:
var eminem = new Human("Marshall Mathers", "M", 45, "aggressive");
eminem.speak.introduce();