Wilt Wilt - 6 months ago 14
Javascript Question

Extend javascript classes and wrap them in a container object

In ES6 you can have your custom classes extend javascript built-in objects. Like this you can make

Array
,
Number
,
String
,
Date
objects with custom methods.

I Was experimenting with this and tried to wrap my objects inside a container object called
My
, simply following the example here from MDN (Mozilla Developer Network). But when I define my custom
Date
class inside the object like this:

var My = {};

class My.Date extends Date {
constructor() {
super();
}

getFormattedDate() {
var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
}
}


I get the following SyntaxError:


Uncaught SyntaxError: Unexpected token .


Here is a fiddle that demonstrates this.

I bet there is some way to work around this but I am not sure how to do that...

Answer

A workaround would be wrapping the logic in a function so the class is declared in the functions local scope and then adding them to the container object My which is declared outside of that function in global scope.
Now you can use the customized objects (extended primitives) without messing with the global objects and in the console they will still look similar (Object names, etc)...

var My = {};

function init(){

    class Date extends window.Date {
        constructor() {
            super();
        }

        getFormattedDate() {
            var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
            return this.getDate() + "-" + months[this.getMonth()] + "-" + this.getFullYear();
        }
    }

    My.Date = Date;

}

init();

Date === window.Date; // true
My.Date === window.Date; // false
new My.Date().getFormattedDate(); // 2-Jun-2016