user734861 user734861 - 4 years ago 90
Javascript Question

How to mimic constructor in JavaScript in OOP style?

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 + '.');
}
};


Now, I am instantiating the above class.

var person1= Object.create(Person);
person1.name = 'personname';
person1.greeting();


How can I mimic a constructor so that when Object.create(Person) creates a new object, the constructor code is automatically computed?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download