jquery - Simple Example of Javascript Inheritance? -


i've searched on , elsewhere simple example of inheritance , can't find one. examples i've seen obscure, complex, or make me uncomfortable. have several service functions share functionality, call baseservice:

function baseservice() {    var loadanimate = function () {       $('#ajax-spinner').show();     };    var loadcomplete = function () {       $('#ajax-spinner').hide();     };    var apiendpoint = function() {       return "http://api.com/api/";     }; }; 

i have other services have functionality:

var documentservice = function() {     // repeated code     var loadanimate = function () {         $('#ajax-spinner').show();     };     var loadcomplete = function () {         $('#ajax-spinner').hide();     };      var apiendpoint = "http://api.com/api/";      var sendrequest = function (payload, callback) {         loadanimate();         // stuff apiendpoint         // call loadcomplete on promise     }; 

how can provide documentservice access items in baseservice?

since javascript prototypical language, doesn't have same sort of class inheritance language like, say, java has. if want simple instance of inheritance, try like:

function baseservice() {   this.loadanimate = function () {     $('#ajax-spinner').show();   };   this.loadcomplete = function () {     $('#ajax-spinner').hide();   };   this.apiendpoint = function() {     return "http://api.com/api/";   }; };  var documentservice = new baseservice(); documentservice.sendrequest() = function() { /* ... */ } 

then, documentservice has of baseservice's members (note this. in baseservice's function declaration instead of var).

if don't want have use new keyword, can create function extend either adds field pointing baseservice (document.baseservice = baseservice) or deep (recursive) copy, adds documentservice.sendrequest.

of course, folks have worked on things ded/klass.


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

c++ - Correct method for redrawing a layered window -

java.util.scanner - How to read and add only numbers to array from a text file -