Object casting
by cillay
HTML
<p>
JSON Object is a Meeting: <span id="jsonIs"></span>.</p>
<p>
new Meeting is a Meeting: <span id="newIs"></span>.</p>
<p>
CastTo Object is a Meeting: <span id="castIs"></span>.</p>
<p>
CastFrom Object is a Meeting: <span id="castFromIs"></span>.</p>
<p>
Number of attendees in my new Meeting: <span id="attendeeCount1"></span>.</p>
<p>
Number of attendees in my castTo Meeting: <span id="attendeeCount2"></span>.</p>
<p>
Number of attendees in my castFrom Meeting: <span id="attendeeCount3"></span>.</p>
<p>
Number of attendees in my castFromArray Meeting: <span id="attendeeCount4"></span>.</p>
JavaScript
// Types
var Meeting = function () {
return (this.constructor == Meeting) ?
(function () {
this.attendees = [];
}).apply(this)
: Meeting.from((arguments.length) ? arguments[0] : {});
};
Object.defineProperty(Meeting.prototype, "attendeeCount", {
get: function () {
return (this.attendees || []).length;
}
});
(function () {
var copy = function (source, target) {
Object.keys(source).forEach(function (key) {
source.hasOwnProperty(key) && (target[key] = source[key]);
});
return target;
};
Object.prototype.as = function (type) {
return copy(this, Object.create(type.prototype));
};
Object.prototype.from = function (object) {
return copy(object, Object.create(this.prototype));
};
Object.prototype.map = function (array) {
return array.map((function (object) { return copy(object, Object.create(this.prototype)); }).bind(this));
};
})();
var jsonMeeting = {
start: "early",
end: "late",
attendees: ["John", "Paul", "George", "Ringo"]
};
var newMeeting = new Meeting();
var castToMeeting = jsonMeeting.as(Meeting);
var castFromMeeting = Meeting(jsonMeeting);
var castFromArray = Meeting.map([jsonMeeting, jsonMeeting]);
console.log(castFromArray);
$("#jsonIs").text(jsonMeeting instanceof Meeting);
$("#newIs").text(newMeeting instanceof Meeting);
$("#castIs").text(castToMeeting instanceof Meeting);
$("#castFromIs").text(castFromMeeting instanceof Meeting);
$("#attendeeCount1").text(newMeeting.attendeeCount);
$("#attendeeCount2").text(castToMeeting.attendeeCount);
$("#attendeeCount3").text(castFromMeeting.attendeeCount);
$("#attendeeCount4").text(castFromArray[0].attendeeCount);