In an OOP way, I am defining a Person "class" as follows:
var Person = {
name: '',
age: 32,
gender: 'male',
interests: ['music', 'skiing'],
bio: function() {
alert(this.name[0] + ' ' + this.name[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
},
greeting: function() {
alert('Hi! I\'m ' + this.name + '.');
}
};
var person1= Object.create(Person);
person1.name = 'personname';
person1.greeting();
You would wrap up the code in a function, and call it there. Object.create
will establish a relationship with the prototype
, but won't call any additional code automatically.
function person(name) {
var person1 = Object.create(Person);
person1.name = name;
return person1;
}
person('personname').greeting();
You should also avoid uppercasing the first letter of variables unless they are functions which should be called using new
. This is a naming convention used only for constructor functions.