Creating a JavaScript object utilizing inheritance
A simple method for JavaScript inheritance is describe below. The referenced code is available at here at my github page.
There is more than one way to complete this programming pattern. I use the following when writing my own JavaScript code.
You first create your base object. in this example it is called page. You then create your child object. In this example it is called mainPage.
Code Example
The page object
function page() {
this.ajax = function() {
return new Ajax();
};
this.doAjax = function(ajax) {
$.ajax({
url : ajax.url,
data : ajax.data,
success: ajax.success
});
};
$.ajaxSetup({
type : “POST”,
dataType : ‘json’
});
return this;
}
The mainPage object
function mainPage() {
this.getMessage = this.ajax();
this.saveData = this.ajax();
this.getMessage.url = ’/ajaxData.php’;
this.getMessage.data = 1;
this.getMessage.success = function(data) { get.obj(mainPage).getMessage.data = data; console.log(data); };
this.saveData.success = function(data) { alert(data.message);
};
this.setupModal = function() {
$(’#launchModal’).click(function() {
$(’#myModal’).modal();
});
this.doAjax(this.getMessage);
$(’#myModal’).on('show.bs.modal’, function(event) {
var button = $(event.relatedTarget) // Button that triggered the // modal
var recipient = button.data('whatever’) // Extract info from data-* // attributes
var modal = $(this)
modal.find(’.modal-title’).text(get.obj(mainPage).getMessage.data.title);
modal.find(’.modal-body’).text(get.obj(mainPage).getMessage.data.message);
})
};
return this;
}
Extend the mainPage object
mainPage.prototype = new page(); mainPage.prototype.constructor = mainPage;
A full working example is in my github page. Here is the link.