Factory based classes in JavaScript

This is a simple factory based class in javascript with a special create method that invokes the predifined Object.create().


var Person = {
typeName: 'Person',
properties: {
firstName:{
range: 'NonEmptyString',
label: 'First Name',
writable: true,
enumerable: true
},
lastName: {
range: 'NonEmptyString',
label: 'Last Name',
writable: true,
enumerable: true
}
},
methods: {
getInitials: function() {
return this.firstName.charAt(0) + this.lastName.charAt(0);
}
},
create: function(slots) {
var obj = null, properties = this.properties;
obj = Object.create(this.methods, properties);
Object.defineProperty(obj, 'type', {value: this, writable: false, enumerable: true});
Object.keys(slots).forEach(function(prop) {
if (properties[prop]) obj[prop] = slots[prop];
});
return obj;
}
}

var Script = Person.create( {firstName:"Java", lastName:"Script"});
Script.getInitials();

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s