JSFiddle - React, Tailwind, and code Playground

by xavierm02

HTML

<div id="console"></div>

JavaScript

// does NOT work
function Point( x, y ) {
    this.x = x;
    this.y = y;
}
Object.defineProperties( Point.prototype, {
    x: {
        get: function ( ) {
            // this would return the stored value
        },
        set: function ( value ) {
             value = parseInt( value );
            // and here, you would want to set "this.x" to value but you can't since this would create an infinite loop
        }
    },
    y: {
        // same here
    }
} );

// code used for testing
var c = document.getElementById( 'console' );
function log( m ) {
    c.appendChild( document.createTextNode( m ) );
    c.appendChild( document.createElement( 'br' ) );
}
function assert( b, m ) {
  if ( !b ) {
    log( m );
  }
}

// tests
try {
    var p = new Point( 1, 2 );
    assert( p.x === 1, 'bad x 1' );
    p.x = 2;
    assert( p.x === 2, 'bad x 2' );
    p.x = '3';
    assert( p.x === 3, 'bad x 3' );
} catch ( e ) {
    log( e );
}
log( 'Done' );