JSFiddle - React, Tailwind, and code Playground

by ccnokes

JavaScript

// JS inheritance

function extend(base, sub) {
  // Avoid instantiating the base class just to setup inheritance
  // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create
  // for a polyfill
  //sub.prototype = Object.create(base.prototype);
    
    //recursive merge of two prototypes, preserve inheritance chain
    //save old one
    var origProto = sub.prototype;
    sub.prototype = Object.create(base.prototype);
    sub.prototype = jQuery.extend(sub.prototype, origProto);
    
    // Remember the constructor property was set wrong, let's fix it
  sub.prototype.constructor = sub;
  // In ECMAScript5+ (all modern browsers), you can make the constructor property
  // non-enumerable if you define it like this instead
  Object.defineProperty(sub.prototype, 'constructor', { 
    enumerable: false, 
    value: sub 
  });
}

function Product(name, price) {
  this.name = name;
  this.price = price;

  if (price < 0)
    throw RangeError('Cannot create product "' + name + '" with a negative price');
  return this;
}
Product.prototype = {
    discount: function(amt) {
        if(amt < 1) {
            this.price = this.price - (this.price * amt);
            return this.price;
        } else {
            throw new Error('discount amt must be less than 1, like 0.3 (30% off)');
        }
    }
};

function Food(name, price) {
  Product.call(this, name, price); //
  this.category = 'food';
  return this;
}
Food.prototype = {
    calcExpiration: function() {
        var exp = Date.now() + 2000;   
        this.exp = exp;
        return this;
    }
};
extend(Product, Food);

var pen = new Product('Pen', 1.32);
pen.discount(0.2);
console.log(pen);

var cheese = new Food('feta', 5);
cheese.discount(0.1);
cheese.calcExpiration();
console.log(cheese);