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([0] + ' ' +[1] + ' is ' + this.age + ' years old. He likes ' + this.interests[0] + ' and ' + this.interests[1] + '.');
greeting: function() {
alert('Hi! I\'m ' + + '.');

Now, I am instantiating the above class.

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

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); = name;
  return person1;


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