Inheritance #1

Using Factory style

by bhupendra negi

JavaScript

function userCreator(name, score) {
  const newUser = Object.create(userFunctions);
  newUser.name = name;
  newUser.score = score;
  return newUser;
}

var userFunctions = {
  sayName: function() {
    console.log(this.name);
  },
  increment: function() {
    this.score++;
  }
}

const user1 = userCreator("Ram", 4);
console.log(user1);
user1.sayName();

/** Subclassing ***/

function paidUserCreator(paidName, paidScore, accountBalance) {

  const paidUser = userCreator(paidName, paidScore);
  // setting __proto__ of paidUser to paidUserFunctions
  Object.setPrototypeOf(paidUser, paidUserFunctions);
  paidUser.accountBalance = accountBalance;
  return paidUser;
}

var paidUserFunctions = {
  increaseBalance: function() {
    this.accountBalance++;
  }
}
Object.setPrototypeOf(paidUserFunctions,userFunctions)
const paidUser1 = paidUserCreator("shyam",40,500);
console.log(paidUser1);
paidUser1.sayName();
paidUser1.increaseBalance();