0

When creating a "child" object class in OOJS, I see two different ways of execution.

First,

function Person(name) {
  this.name = name;
  this.sayHi = function(){
    alert("Hi");
  }
}

function Teacher(name) {
  Person.call(call, name);
  }
}

var teacher1 = new Teacher("Tom");

Second,

function Person(name) {
  this.name = name;
}

Person.prototype.sayHi = function() {
  alert("Hi");
}

function Teacher(name) {
   //same as the first example
}

Teacher.prototype = Object.create(Person.prototype);
Object.defineProperty(Teacher.prototype, 'constructor', { 
  value: Teacher, 
  enumerable: false, // so that it does not appear in 'for in' loop
  writable: true 
});

The second method seems unnecessarily complicated. I am still able to access Teacher.prototype through both methods. What's the reasoning behind the second method?

Kevvv
  • 3,655
  • 10
  • 44
  • 90
  • 1
    You don't have to instantiate a new function instance for each constructed object. – Pointy Feb 21 '19 at 21:52
  • 2
    Your second snippet is missing the definition of the `Teacher`? Also did you duplicate the `sayHi` definition in the first snippet on purpose? – Bergi Feb 21 '19 at 21:55
  • 1
    So they the same function can be shared among all instances and not created for each one. – ibrahim mahrir Feb 21 '19 at 21:55
  • 2
    The `Object.defineProperty` thing is indeed unnecessarily complicated - it's not strictly required for anything, it's just a good practice. – Bergi Feb 21 '19 at 21:56
  • Doesn't Person.call(name) essentially allow you to access Person.prototype instead of the extra step Teacher.prototype = Object.create(Person.prototype);? – Kevvv Feb 21 '19 at 22:05

0 Answers0