Using the new( ) Operator on Constructor Functions

Video

JavaScript Notes

JavaScript
    // using “new” with Constructor functions
    // new does 4 things:
    // new object created
    // new object is prototype linked
    // new object set as “this” binding
    // if no return statement exists then a copy of the object is rendered
    log = console.log;
    
    // Car, here, is the Constructor function
    function Car(make, model){
          log(this);			            // this refers to the object that called the function
          let props = {               // variable prop doesn't exist outside function as it is locally scoped
                   make,
                   model
                 };
          let info = function ( ){    // variable info doesn't exist outside function as it is locally scoped
               return this.props;
          }
    }
    
    let c1 = Car('Honda', 'Accord');
    let c2 = new Car('Tesla', 'Model 3');
    
    log(c1);		// should return undefined as the function does not return anything, and assigns 'undefined' to c1
    log(c2);		// should return a new object, Car { } object, and assign it to c2

    Car.prototype.info = function ( ){ // creates a property called info and assigns it to ever Car object
            return this.props;
    }