JSFiddle - React, Tailwind, and code Playground

OOP-: Ch4- Constructors and Prototypes

by nickadeemus2002

JavaScript

/**
 * OOP: ch.4 - Constructors and Prototypes
 * =====================================================
 * Constructors are Functions
 */
 


/*
* Constructor:
* ====================
*	Objects created with the same constructor contain the same
* properties and methods.
*/


//Person Contstructor
function Person(name){
	//props
  this.name = name;
  this.sayName = function(){
  	return this.name
  }
  
/*
* You can also explicitly call return inside of a constructor. 
* If the returned value is an object, it will be returned 
* instead of the newly created object instance. If the returned
* value is a primitive, the newly created object is used and 
* the returned value is ignored.
*/
	//return ???
}

var p1 = new Person();
var p2 = new Person();

// show objs
console.log("Person => p1: ", p1);
console.log("Person => p2: ", p2);
/*
* you are advised to use instanceof to check the 
* type of an instance. This is because the constructor 
* property can be overwritten and therefore may not 
* be completely accurate.
*/

// instance of Person?
console.log("p1 instanceof Person => ", p1 instanceof Person);  //true
console.log("p2 instanceof Person => ", p2 instanceof Person);  //true
// constructor?
console.log("p1.constructor: ", p1.constructor);        								// function
console.log("p1.constructor === Person: ", p1.constructor === Person);  //true
console.log("p2.constructor: ", p2.constructor);												//function
console.log("p2.constructor === Person: ", p2.constructor === Person);  //true

console.log('----------------------------------------------------------------------------------------------------------');

//ES5 Person Constructor
function es5Person(name) {
	
  //props
	Object.defineProperty(this, "name", {
		get: function() {
			return name;
		},
		set: function(newName) {
			name = newName;
		},
		enumerable: true,
		configurable: true
	});
   
  //return 5; 
}

//Person methods on the prototype
es5Person.prototype = {
	//constructor:...