Rectangle 27 0

jquery Simple Example of Javascript Inheritance?


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() { /* ... */ }

If you don't want to have to use the new keyword, you can create a function extend either adds a field pointing to baseservice (document.baseservice = baseservice) or does a deep (recursive) copy, then adds documentservice.sendRequest.

JS works very differently to classical inheritance languages. Strongly advice that the OP read Crockford's "JavaScript the Good Parts" book. amazon.com/JavaScript-Good-Parts-Douglas-Crockford/dp/

Of course, folks have already worked on this with things like ded/klass.

Since Javascript is a prototypical language, it doesn't have the same sort of class inheritance that a language like, say, Java has. If you want a very simple instance of inheritance, you could try something like:

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

Note