Notizen

how to create a deep copy of a 2D Array with a ES6 syntax…

arr1 = [[0, 1], [10, 11]];

// tiefe Kopie von 2D-Array mit map and spread operator...
arr2 = arr1.map(e => [...e]);

console.log('arr1', arr1);
console.log('arr2', arr2);

arr1[0][0] = 'start!';
arr2[1][1] = 'end!';

console.log('arr1', arr1);
console.log('arr2', arr2);

factory function vs. constructor function

/*
  the factory way to create an object in JS...
*/
console.log(` Ein detailliertes Beispiel einer 'factory function'...`);

function punktFactory(p1, p2) {
  // object creation
  const obj = {};

  // properties assigning
  obj.x = p1;
  obj.y = p2;
  
  // returning the object
  return obj;
}

let punkt1 = punktFactory(1, 2);
console.info(punkt1);

console.log(`punkt1.__proto__: ${punkt1.__proto__}`);

console.log(`punktFactory.prototype: ${punktFactory.prototype}`);
console.log(`punktFactory.__proto__: ${punktFactory.__proto__}`);


/*
  the constructor way to create an object in JS...
*/
console.log(`\n\nEin Beispiel einer 'constructor function'...`);

function PunktConstructor(p1, p2) {
  // no need to object creation
  
  // properties assigning with the 'this' keyword
  this.x = p1;
  this.y = p2;
  
  // no need to return the object
  // instead by calling the new operator need to be used
  // to avoid assigning the object ot the global object...
}

let punkt2 = new PunktConstructor(1, 2);
console.info(punkt2);

console.log(`punkt2.__proto__: ${punkt2.__proto__}`);

console.log(`PunktConstructor.prototype: ${PunktConstructor.prototype}`);
console.log(`PunktConstructor.__proto__: ${PunktConstructor.__proto__}`);

the output of the code snippet would be something like this:

" Ein detailliertes Beispiel einer 'factory function'..."
[object Object] {
  x: 1,
  y: 2
}
"punkt1.__proto__: [object Object]"
"punktFactory.prototype: [object Object]"
"punktFactory.__proto__: function () { [native code] }"


"Ein Beispiel einer 'constructor function'..."
[object Object] {
  x: 1,
  y: 2
}
"punkt2.__proto__: [object Object]"
"PunktConstructor.prototype: [object Object]"
"PunktConstructor.__proto__: function () { [native code] }"