JSFiddle - React, Tailwind, and code Playground
by marcosc
JavaScript
(function(){
"use strict";
var name = "CustomThing";
//makes us custom "actions" - could be anything
function CustomAction ( id ) {
this.x = Math.random();
this.y = Math.random();
var id = "This has id " + id
//define a read only getter, for fun
Object.defineProperty(this, "id", {get: function(){return id}})
}
//implement it
var func = new Function("name", "action",
" return function " + name + "(id){ "+
//only allow creation with new keyword
" if(this === window) throw TypeError('Invalid constructor! try using new');" +
" return Object.create(new action(id)); };"
)(name, CustomAction);
//Add it to the window object;
Object.defineProperty(window, name, {value: func } )
})();
//Some Tests
try{
CustomThing();
}catch(e){
//TypeError: Invalid constructor! try using new
console.log(e)
}
//Gives you a CustomAction object
var cust = new CustomThing("test");
//check the console
console.dir(cust);
console.log(cust.x);
console.log(cust.y);
console.log(cust.id);