JSFiddle - React, Tailwind, and code Playground

by tonyleeper

JavaScript

// why Object.create is preferred over new

var Person = function (name) {
    if (typeof name === 'undefined' || name === null) {
        throw new Error('name is null or undefined');
    }
    
    this.name = name;
};

Person.prototype.introduce = function () {
    console.log('Hello, my name is ' + this.name);
};

var tony = new Person('Tony');
tony.introduce();

var Ninja = function (name, attackPower) {
    Person.call(this, name);
    this.attackPower = attackPower;
};

Ninja.prototype = Object.create(Person.prototype);
Ninja.prototype.constructor = Ninja;

Ninja.prototype.kick = function () {
    console.log(this.name + ' roundhouse kicks you in the face with force of ' + this.attackPower + ' N');
};

var chuckNorris = new Ninja('Chuck Norris', Infinity);
chuckNorris.introduce();
chuckNorris.kick();

console.log(chuckNorris instanceof Ninja);
console.log(chuckNorris instanceof Person);
console.log(chuckNorris.constructor);