Skip to content

Instantly share code, notes, and snippets.

@reinvanoyen
Created March 10, 2017 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save reinvanoyen/30e480a65302a59e92d6d082f8826cef to your computer and use it in GitHub Desktop.
Save reinvanoyen/30e480a65302a59e92d6d082f8826cef to your computer and use it in GitHub Desktop.
Simple Javascript class system with inheritance and property/method visibility (public/private)
"use strict";
const module = function( f ) {
let pub = {};
f( pub );
return pub;
};
const Class = {
create: function( data ) {
let currentObject = Object.create( this );
currentObject = Object.assign( currentObject, data );
return currentObject;
},
extend: function( data ) {
return Object.assign( this.create( this ), data );
}
};
const Component = Class.create( module( pub => {
pub.data = {};
pub.load = function( data ) {
this.data = data;
};
} ) );
const SingleValueComponent = Component.extend( module( pub => {
pub.value = '';
pub.field = '';
pub.create = function( field ) {
this.field = field;
return Component.create.call( this );
};
pub.load = function( data ) {
Component.load.call( this, data );
this.value = this.data[ this.field ];
};
} ) );
const StringEdit = SingleValueComponent.extend( module( pub => {
pub.type = 'StringEdit';
pub.build = function() {
console.log( this.type + ' - ' + this.value );
};
} ) );
const StringView = SingleValueComponent.extend( module( pub => {
pub.type = 'StringView';
pub.build = function() {
console.log( this.type + ' - ' + this.value );
};
} ) );
const BetterStringView = StringView.extend( module( pub => {
pub.type = 'BetterStringView';
pub.build = function() {
StringView.build.call( this );
};
} ) );
// Implementations
let data = {
title: 'Over ons',
slug: 'over-ons',
description: 'Dit is de over ons pagina'
};
let string = StringEdit.create( 'title' );
string.load( data );
let slug = StringView.create( 'slug' );
slug.load( data );
let description = BetterStringView.create( 'description' );
description.load( data );
string.build();
slug.build();
description.build();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment