0

What exactly is the 'constructor' in the following? That is, what does the Object.create do vs. calling the constructor? Does the constructor actually execute the function name, or what magic happens there?

function greet(name) {
    this.print = function print() {console.log('hey!', name)};
}

// why's it required to create an object of the funcion.prototype and again initialize the constructor?
let y = Object.create(greet.prototype);
y.constructor('Bob');
y.print();

// this part makes sense to me.
let z = new greet('Bob');
z.print();

Also, if I were to put the print() method outside the function, how would I access the name? For example:

function greet(name) {
    this.name = name;
}
greet.prototype.print = () => {console.log('hey!', this.name)};
// 'hey! undefined'
samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • It's not necessary, but when there's no properties in `greet.prototype`, you would get an empty object, calling the constructor assgins the own properties to the newly-created object. – Teemu Feb 01 '22 at 19:11
  • 1
    "*What exactly is the 'constructor' in the following?*" -`y.constructor` is inherited from `greet.prototype.constructor` which is `greet`. Same as `greet.call(c, 'Bob')`. – Bergi Feb 01 '22 at 19:14
  • *"again initialize the constructor"*: what does that mean? The constructor is defined by the `function` statement. It does not get initialised again. If you meant "invoked" instead of "initialized", then it is not invoked *again*. It is just invoked, as `Object.create` does not invoke a constructor. – trincot Feb 01 '22 at 19:23
  • 1
    Defining a prototype property works fine, you should just not define it using arrow function, which binds a different `this` than you think. – Teemu Feb 01 '22 at 19:32
  • https://stackoverflow.com/questions/34361379/are-arrow-functions-and-functions-equivalent-interchangeable – Teemu Feb 01 '22 at 19:39

0 Answers0