JSFiddle - React, Tailwind, and code Playground

by grahamhunter

HTML

<div id="output"></div>

JavaScript

// declare parent object as global variable
var parent = null;

$(document).ready(function() {

    // instantiate parent
    parent = new Foo();
    
    // uncomment to instantiate child separately
    // child = new ChildFoo();

    // write to log from outside parent (shows scope is global)
    parent.log.write(parent.x)
    parent.log.write(child.x);


});

function Foo() {

    // instantiate logger as child of parent
    this.log = new Logger("output");

    // write a quick message
    this.log.write("Foo constructor");

    // set value of x
    this.x = 1;

    // instantiate child object
    this.child = new ChildFoo;

}

// child object definition
function ChildFoo() {

    // why is parent.log == null here?
    parent.log.write("Child constructor");
    
    // this reference to parent also fails
    // this.x = 10 * parent.x;
    
    this.x = 10;

}

// log object definition
function Logger(container) {
    
    // store reference to dom container
    this.container = container;
    
}

// method to write message to dom
Logger.prototype.write = function(message) {
    $("#" + this.container).append("[" + new Date() + "] " + message + "<br>");
}